Check if elements of a Binary Matrix can be made alternating | 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
function PosCheck ( a , n , m , check ) { for ( let i = 0 ; i < n ; i ++ ) { for ( let 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 ; } function fill ( a , n , m , odd , even ) { for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { if ( ( i + j ) & 1 ) { a [ i ] [ j ] = odd ; } else { a [ i ] [ j ] = even ; } } } } function findPossibleGrid ( n , m , a ) { let flag = true ; let k = - 1 , o = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let 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 , " " ) ; if ( flag ) { fill ( a , n , m , " " , " " ) ; } else { flag = PosCheck ( a , n , m , " " ) ; if ( flag ) { fill ( a , n , m , " " , " " ) ; } } } else { let h = " " ; for ( let i = 0 ; i < m ; i ++ ) { a [ 0 ] [ i ] = h ; if ( h == " " ) { h = " " ; } else { h = " " ; } } for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { if ( i - 1 < 0 ) { continue ; } if ( a [ i - 1 ] [ j ] == " " ) { a [ i ] [ j ] = " " ; } else { a [ i ] [ j ] = " " ; } } } flag = true ; } if ( ! flag ) { document . write ( " " ) ; } else { document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { document . write ( a [ i ] [ j ] ) ; } document . write ( " " ) ; } } } let n = 4 , m = 4 ; let grid = [ [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , [ " " , " " , " " , " " ] , ] ; findPossibleGrid ( n , m , grid ) ;