Replace specified matrix elements such that no two adjacent elements are equal | Function to check if current position is safe or not ; Directions for adjacent cells ; Check if any adjacent cell is same ; Current index is valid ; Recursive function for backtracking ; Free cell ; All positions covered ; If position is valid for 1 ; If position is valid for 2 ; Recursive call for next unoccupied position ; If above conditions fails ; Function to print valid matrix ; Driver code ; Give dimensions ; Function call
function issafe ( v , i , j , n , m , ch ) { let rowN = [ 1 , - 1 , 0 , 0 ] ; let colN = [ 0 , 0 , 1 , - 1 ] ; for ( let k = 0 ; k < 4 ; k ++ ) { if ( i + rowN [ k ] >= 0 && i + rowN [ k ] < n && j + colN [ k ] >= 0 && j + colN [ k ] < m && v [ i + rowN [ k ] ] [ j + colN [ k ] ] == ch ) { return false ; } } return true ; } function place ( v , n , m ) { let i = 0 , j = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( v [ i ] [ j ] == ' ' ) { break ; } } if ( j != m ) { break ; } } if ( i == n && j == m ) { return true ; } if ( issafe ( v , i , j , n , m , ' ' ) ) { v [ i ] [ j ] = ' ' ; if ( place ( v , n , m ) ) { return true ; } v [ i ] [ j ] = ' ' ; } if ( issafe ( v , i , j , n , m , ' ' ) ) { v [ i ] [ j ] = ' ' ; if ( place ( v , n , m ) ) { return true ; } v [ i ] [ j ] = ' ' ; } return false ; } function printMatrix ( arr , n , m ) { place ( arr , n , m ) ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { document . write ( arr [ i ] [ j ] ) ; } document . write ( " " ) ; } } let arr = [ [ ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' ] , ] ; let n = 4 , m = 4 ; printMatrix ( arr , n , m ) ;