Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | Function to return number of moves to convert matrix into chessboard ; Size of the matrix ; Traverse the matrix ; Initialize rowSum to count 1 s in row ; Initialize colSum to count 1 s in column ; To store no . of rows to be corrected ; To store no . of columns to be corrected ; Traverse in the range [ 0 , N - 1 ] ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if N is odd ; Check if column required to be corrected is odd and then assign N - colSwap to colSwap ; Check if rows required to be corrected is odd and then assign N - rowSwap to rowSwap ; Take min of colSwap and N - colSwap ; Take min of rowSwap and N - rowSwap ; Finally return answer ; Given matrix ; Function Call ; Prvar answer
function minSwaps ( b ) { var n = b . length ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) == 1 ) { return - 1 ; } } } var rowSum = 0 ; var colSum = 0 ; var rowSwap = 0 ; var colSwap = 0 ; for ( i = 0 ; i < n ; i ++ ) { rowSum += b [ i ] [ 0 ] ; colSum += b [ 0 ] [ i ] ; var cond1 = 0 ; var cond2 = 0 ; if ( b [ i ] [ 0 ] == i % 2 ) cond1 = 1 ; if ( b [ 0 ] [ i ] == i % 2 ) cond2 = 1 ; rowSwap += cond1 ; colSwap += cond2 ; } if ( rowSum != n / 2 && rowSum != ( n + 1 ) / 2 ) return - 1 ; if ( colSum != n / 2 && colSum != ( n + 1 ) / 2 ) return - 1 ; if ( n % 2 == 1 ) { if ( ( colSwap % 2 ) == 1 ) colSwap = n - colSwap ; if ( ( rowSwap % 2 ) == 1 ) rowSwap = n - rowSwap ; } else { colSwap = Math . min ( colSwap , n - colSwap ) ; rowSwap = Math . min ( rowSwap , n - rowSwap ) ; } return ( rowSwap + colSwap ) / 2 ; } var M = [ [ 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 1 ] ] ; var ans = minSwaps ( M ) ; document . write ( ans ) ;