Check if elements of a Binary Matrix can be made alternating | C ++ program for the above approach ; Function to check for the grid in one of the alternating ways ; Iterate over the range ; Iterate over the range ; ( i + j ) % 2 == 1 cells should be with the character check and the rest should be with the other character ; Function to fill the grid in a possible way ; Function to find if the grid can be made alternating ; If grid contains atleast one 1 or 0 ; Fill the grid in any possible way ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool PosCheck ( char a [ ] [ 1001 ] , int n , int m , char check ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] == ' * ' ) { continue ; } else { if ( ( ( i + j ) & 1 ) && a [ i ] [ j ] != check ) { return false ; } if ( ! ( ( i + j ) & 1 ) && a [ i ] [ j ] == check ) { return false ; } } } } return true ; } void fill ( char a [ ] [ 1001 ] , int n , int m , char odd , char even ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( ( i + j ) & 1 ) { a [ i ] [ j ] = odd ; } else { a [ i ] [ j ] = even ; } } } } void findPossibleGrid ( int n , int m , char a [ ] [ 1001 ] ) { bool flag = true ; int k = -1 , o = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] != ' * ' ) { k = i ; o = j ; break ; } } if ( k != -1 ) { break ; } } if ( k != -1 ) { flag = PosCheck ( a , n , m , '1' ) ; if ( flag ) { fill ( a , n , m , '1' , '0' ) ; } else { flag = PosCheck ( a , n , m , '0' ) ; if ( flag ) { fill ( a , n , m , '0' , '1' ) ; } } } else { char h = '1' ; for ( int i = 0 ; i < m ; i ++ ) { a [ 0 ] [ i ] = h ; if ( h == '1' ) { h = '0' ; } else { h = '1' ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( i - 1 < 0 ) { continue ; } if ( a [ i - 1 ] [ j ] == '1' ) { a [ i ] [ j ] = '0' ; } else { a [ i ] [ j ] = '1' ; } } } flag = true ; } if ( ! flag ) { cout << " NO STRNEWLINE " ; } else { cout << " YES STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << a [ i ] [ j ] ; } cout << endl ; } } } int main ( ) { int n = 4 , m = 4 ; char grid [ ] [ 1001 ] = { { ' * ' , ' * ' , '1' , '0' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , '0' , '1' } } ; findPossibleGrid ( n , m , grid ) ; return 0 ; }