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 ; Driver Code ; Given matrix ; Function Call ; Print answer
def minSwaps ( b ) : NEW_LINE INDENT n = len ( b ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT rowSum = 0 NEW_LINE colSum = 0 NEW_LINE rowSwap = 0 NEW_LINE colSwap = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT rowSum += b [ i ] [ 0 ] NEW_LINE colSum += b [ 0 ] [ i ] NEW_LINE rowSwap += b [ i ] [ 0 ] == i % 2 NEW_LINE colSwap += b [ 0 ] [ i ] == i % 2 NEW_LINE DEDENT if ( rowSum != n // 2 and rowSum != ( n + 1 ) // 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( colSum != n // 2 and colSum != ( n + 1 ) // 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT if ( colSwap % 2 ) : NEW_LINE INDENT colSwap = n - colSwap NEW_LINE DEDENT if ( rowSwap % 2 ) : NEW_LINE INDENT rowSwap = n - rowSwap NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT colSwap = min ( colSwap , n - colSwap ) NEW_LINE rowSwap = min ( rowSwap , n - rowSwap ) NEW_LINE DEDENT return ( rowSwap + colSwap ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = [ [ 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 1 ] ] NEW_LINE ans = minSwaps ( M ) NEW_LINE print ( ans ) NEW_LINE DEDENT