Check if elements of a Binary Matrix can be made alternating | 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
function createGrid ( grid , is1 , N , M ) { for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M ; j ++ ) { if ( is1 ) { grid [ i ] [ j ] = " " ; is1 = false ; } else { grid [ i ] [ j ] = " " ; is1 = true ; } } if ( M % 2 == 0 ) is1 = ! is1 ; } } function testGrid ( testGrid , Grid , N , M ) { for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M ; j ++ ) { if ( Grid [ i ] [ j ] != " " ) { if ( Grid [ i ] [ j ] != testGrid [ i ] [ j ] ) { return false ; } } } } return true ; } function printGrid ( grid , N , M ) { for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M ; j ++ ) { document . write ( grid [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } function findPossibleGrid ( N , M , grid ) { let gridTest1 = new Array ( N ) . fill ( 0 ) . map ( ( ) => new Array ( 1001 ) ) ; let gridTest2 = new Array ( N ) . fill ( 0 ) . map ( ( ) => new Array ( 1001 ) ) ; createGrid ( gridTest1 , true , N , M ) ; createGrid ( gridTest2 , false , N , M ) ; if ( testGrid ( gridTest1 , grid , N , M ) ) { document . write ( " " ) ; printGrid ( gridTest1 , N , M ) ; } else if ( testGrid ( gridTest2 , grid , N , M ) ) { document . write ( " " ) ; printGrid ( gridTest2 , N , M ) ; } else { document . write ( " " ) ; } } let N = 4 , M = 4 ; let grid = [ [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , ] ; findPossibleGrid ( N , M , grid ) ;