Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | C ++ program for the above approach ; 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 ; Driver Code ; Given matrix ; Function Call ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( vector < vector < int > > & b ) { int n = b . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) return -1 ; } } int rowSum = 0 ; int colSum = 0 ; int rowSwap = 0 ; int colSwap = 0 ; for ( int i = 0 ; i < n ; i ++ ) { rowSum += b [ i ] [ 0 ] ; colSum += b [ 0 ] [ i ] ; rowSwap += b [ i ] [ 0 ] == i % 2 ; colSwap += b [ 0 ] [ i ] == i % 2 ; } 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 ) colSwap = n - colSwap ; if ( rowSwap % 2 ) rowSwap = n - rowSwap ; } else { colSwap = min ( colSwap , n - colSwap ) ; rowSwap = min ( rowSwap , n - rowSwap ) ; } return ( rowSwap + colSwap ) / 2 ; } int main ( ) { vector < vector < int > > M = { { 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 } , { 1 , 0 , 0 , 1 } , { 1 , 0 , 0 , 1 } } ; int ans = minSwaps ( M ) ; cout << ans ; }