human
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"
Solution in Python:
assistant
#Here is code to minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct and the other steps required.
 def minSwaps ( b ) :
	n = len ( b )
	for i in range ( n ) :
		for j in range ( n ) :
			if ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) :
				return - 1
	rowSum = 0
	colSum = 0
	rowSwap = 0
	colSwap = 0
	for i in range ( n ) :
		rowSum += b [ i ] [ 0 ]
		colSum += b [ 0 ] [ i ]
		rowSwap += b [ i ] [ 0 ] == i % 2
		colSwap += b [ 0 ] [ i ] == i % 2
	if ( rowSum != n // 2 and rowSum != ( n + 1 ) // 2 ) :
		return - 1
	if ( colSum != n // 2 and 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
if __name__ == " _ _ main _ _ " :
	M = [ [ 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 1 ] ]
	ans = minSwaps ( M )
	print ( ans )