![]() |
VOOZH | about |
Given a matrix of size N * N containing only 0s and 1s, where 0 represents white and 1 represents black. The task is to minimize the number of swaps to form a valid chessboard. Only 2 rows or 2 columns can be swapped with each other.
If it is impossible to form a chessboard, return -1.
Examples:
Input: {{0, 1, 1, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}}
Output: 2
Explanation: One potential sequence of moves is shown below,
The first move swaps the first and second columns.
The second move swaps the second and third row.Input: {{0, 1, 0}, {1, 0, 1}, {1, 1, 0}}
Output: -1
Approach: The problem can be solved based on the following properties of chessboard and the observation:
Properties of chess board:
- In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other, the same is true for columns.
A corollary is that any rectangle inside the board with corners top left, top right, bottom left, and bottom right must be 4 zeros or 2 ones and 2 zeros or 4 zeros.- Another important property is that every row and column has half ones. Assume the board is N * N:
- If N = 2 * K, every row and every column has K ones and K zeros.
- If N = 2 * K + 1, every row and every column has K ones and K + 1 zeros or K + 1 ones and K zeros.
Since the swap process does not break these properties, for a given board to be valid, these properties must hold.
These two conditions are necessary and sufficient conditions for a valid chessboard.Swap Count:
To calculate the number of swaps required to create the chessboard, Iterating over first row and first column and check for alternate whites and blacks.
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach.
2
Time complexity: O(N2)
Auxiliary Space: O(1)