Check if elements of a Binary Matrix can be made alternating | C ++ program for the above approach ; Function to create the possible grids ; Function to test if any one of them matches with the given 2 - D array ; Function to print the grid , if possible ; Function to check if the grid can be made alternating or not ; Grids to store the possible grids ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createGrid ( char grid [ ] [ 1001 ] , bool is1 , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( is1 ) { grid [ i ] [ j ] = '0' ; is1 = false ; } else { grid [ i ] [ j ] = '1' ; is1 = true ; } } if ( M % 2 == 0 ) is1 = ! is1 ; } } bool testGrid ( char testGrid [ ] [ 1001 ] , char Grid [ ] [ 1001 ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( Grid [ i ] [ j ] != ' * ' ) { if ( Grid [ i ] [ j ] != testGrid [ i ] [ j ] ) { return false ; } } } } return true ; } void printGrid ( char grid [ ] [ 1001 ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << grid [ i ] [ j ] << " ▁ " ; } cout << endl ; } } void findPossibleGrid ( int N , int M , char grid [ ] [ 1001 ] ) { char gridTest1 [ N ] [ 1001 ] , gridTest2 [ N ] [ 1001 ] ; createGrid ( gridTest1 , true , N , M ) ; createGrid ( gridTest2 , false , N , M ) ; if ( testGrid ( gridTest1 , grid , N , M ) ) { cout << " Yes STRNEWLINE " ; printGrid ( gridTest1 , N , M ) ; } else if ( testGrid ( gridTest2 , grid , N , M ) ) { cout << " Yes STRNEWLINE " ; printGrid ( gridTest2 , N , M ) ; } else { cout << " No STRNEWLINE " ; } } int main ( ) { int N = 4 , M = 4 ; char grid [ ] [ 1001 ] = { { ' * ' , ' * ' , '1' , '0' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , '0' , '1' } } ; findPossibleGrid ( N , M , grid ) ; return 0 ; }