Transform To Chessboard Problem
Description
LeetCode Problem 782.
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
Input: board = [[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.
The first move swaps the first and second column.
The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]]
Output: 0
Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]]
Output: -1
Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Constraints:
- n == board.length
- n == board[i].length
- 2 <= n <= 30
- board[i][j] is either0 or 1.
Solution
Approach: Check the Structure, Then Fix One Row and One Column
A row swap only reorders the rows, and a column swap reorders the cells of every row in the same way, so neither changes whether two rows are equal or complements of each other. A chessboard has exactly two kinds of rows, 0101... and 1010..., each the complement of the other. So the board can only be fixed if every row equals the first row or its complement. In terms of cells: board[i][j] ^ board[i][0] ^ board[0][j] ^ board[0][0] must be 0 for all i, j. If any cell breaks this, return -1.
Once that holds, rows and columns are independent:
- A row is identified by its first cell, so row swaps just reorder the first column, and the rows are right when the first column alternates.
- Likewise, column swaps reorder the first row, which must alternate.
The answer is minSwaps(first column) + minSwaps(first row), where minSwaps(line) is the fewest swaps that make a 0/1 line alternate:
- The counts of
0s and1s must differ by at most one; otherwise return-1. (This also rules out boards like[[1,0],[1,0]]where all rows are the same.) - Count
mismatches: positions whereline[i] != i % 2, comparing against0101.... Against1010...the count isn - mismatches. - If
nis even, either pattern works: take the smaller count. Ifnis odd, only the pattern starting with the more common value fits, and it is the one whose mismatch count is even; use that one. - Each swap fixes two misplaced positions, so return
mismatches / 2.
The odd case is the trap: min(mismatches, n - mismatches) can pick an odd count, a pattern the line can never reach.
Complexity: O(n2) time for the structure check and O(n) extra space, where n is the side length of board.
class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
n = len(board)
# Swaps keep every row equal to the first row or to its complement, and a
# chessboard needs exactly that. The XOR is 1 when row i breaks this rule at column j.
for i in range(n):
for j in range(n):
if board[i][j] ^ board[i][0] ^ board[0][j] ^ board[0][0]:
return -1
# Column swaps reorder the first row; row swaps reorder the first column.
first_row = board[0]
first_col = [board[i][0] for i in range(n)]
col_swaps = self.min_swaps(first_row)
row_swaps = self.min_swaps(first_col)
if col_swaps == -1 or row_swaps == -1:
return -1
return col_swaps + row_swaps
def min_swaps(self, line: List[int]) -> int:
"""Fewest swaps that make line alternate 0, 1, 0, 1... or 1, 0, 1, 0..., or -1."""
n = len(line)
ones = sum(line)
if abs(2 * ones - n) > 1:
return -1 # the counts of 0s and 1s must differ by at most one
# Positions that differ from the pattern 0, 1, 0, 1...
mismatches = 0
for i, value in enumerate(line):
if value != i % 2:
mismatches += 1
if n % 2 == 1:
# Only one pattern has the right counts: the one with an even number of mismatches.
if mismatches % 2 == 1:
mismatches = n - mismatches # use the pattern 1, 0, 1, 0... instead
else:
mismatches = min(mismatches, n - mismatches)
return mismatches // 2 # one swap fixes two misplaced positions
Now write it from memory
Close the write-up and solve it yourself against the tests.