Check if elements of a Binary Matrix can be made alternating | Java 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
import java . io . * ; class GFG { public static void createGrid ( char [ ] [ ] grid , boolean 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 ; } } public static boolean testGrid ( char [ ] [ ] testGrid , char [ ] [ ] Grid , 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 ; } public static void printGrid ( char [ ] [ ] grid , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { System . out . print ( grid [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void findPossibleGrid ( int N , int M , char [ ] [ ] grid ) { char [ ] [ ] gridTest1 = new char [ N ] [ 1001 ] ; char [ ] [ ] gridTest2 = new char [ N ] [ 1001 ] ; createGrid ( gridTest1 , true , N , M ) ; createGrid ( gridTest2 , false , N , M ) ; if ( testGrid ( gridTest1 , grid , N , M ) ) { System . out . println ( " Yes " ) ; printGrid ( gridTest1 , N , M ) ; } else if ( testGrid ( gridTest2 , grid , N , M ) ) { System . out . println ( " Yes " ) ; printGrid ( gridTest2 , N , M ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { int N = 4 , M = 4 ; char [ ] [ ] grid = { { ' * ' , ' * ' , '1' , '0' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , '0' , '1' } } ; findPossibleGrid ( N , M , grid ) ; } }