You get an n × n grid board of 0s and 1s. In one move you may swap any two whole rows, or any two whole columns.
Return the fewest moves that turn board into a chessboard, where no two cells that touch side by side or top to bottom hold the same value. Either corner value is fine. If no sequence of moves works, return -1.
Example 1
Input: board = [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]] Output: 2 Why: swap columns 1 and 2, then rows 1 and 2
2 more examples and the constraints
Example 2
Input: board = [[1, 0, 1], [1, 0, 1], [0, 1, 0]] Output: 1 Why: the columns already alternate; swap rows 1 and 2
Example 3
Input: board = [[1, 1], [0, 1]] Output: -1 Why: row 1 is neither row 0 nor its opposite
Constraints
- 2 ≤ n ≤ 30
- board is n × n
- Every board[i][j] is 0 or 1.
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Group the line patternsO(n²)
- First row and column onlyO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 30 | Verdict |
|---|---|---|---|
| Group the line patterns | O(n²) | Fine; builds and hashes 2n strings | |
| First row and column only | O(n²) | Best; one pass, no extra memory |
n = side length of the board.
Edge cases to test
- Already a chessboard. Both counts are 0 (or n for the other target): the answer is 0.
- Odd n. Only the target whose corner matches the majority value is reachable; pick the even mismatch count.
- Unbalanced row. A row with three 1s out of four can never alternate: -1.
- Three row kinds. If some row is neither row 0 nor its opposite, swaps cannot fix it: -1.
- 2 × 2. Only [[0,1],[1,0]] and [[1,0],[0,1]] work as given, and [[0,1],[0,1]] style boards return -1.
Common mistakes
- Trying to simulate swaps or search over permutations, which is factorial in n.
- For odd n, taking the minimum of both targets instead of the one with an even mismatch count.
- Checking only that rows come in two kinds and forgetting each line must have balanced 1s and 0s.
How to talk through it
- 1Clarify. Are both corner colourings allowed? Is it impossible ever, and then -1? (Yes.)
- 2Find the invariant. Swaps never change which values a row holds, and equal or opposite rows stay that way.
- 3State the conditions. Two kinds of rows, opposite, balanced counts; each row balanced in 1s and 0s; same for columns.
- 4Count swaps. Rows and columns are independent; mismatches against 1010... halved, with parity for odd n.
- 5Test out loud. Try Example 1 (2), a 3 × 3 that needs one row swap, and a board with a third row kind (-1).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?