#782
Hard Algorithms Transform to chessboard
Array Math Bit Manipulation Matrix
51.2% acceptance
Feb 21, 2026
373
313
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.
Solution
Rust
Time O(n²)
Space O(1)
/*
* 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 either 0 or 1.
*/
impl Solution {
pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {
let n = board.len();
// Validity: board[i][j] XOR board[0][j] XOR board[i][0] XOR board[0][0] == 0
for i in 0..n {
for j in 0..n {
if (board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) != 0 {
return -1;
}
}
}
let row_ones = (0..n).filter(|&i| board[i][0] == 1).count();
let col_ones = (0..n).filter(|&j| board[0][j] == 1).count();
if row_ones > (n+1)/2 || n - row_ones > (n+1)/2 { return -1; }
if col_ones > (n+1)/2 || n - col_ones > (n+1)/2 { return -1; }
let row_mismatch = (0..n).filter(|&i| board[i][0] != (i % 2) as i32).count();
let col_mismatch = (0..n).filter(|&j| board[0][j] != (j % 2) as i32).count();
let row_swaps = if n % 2 == 1 {
if row_mismatch % 2 == 0 { row_mismatch / 2 } else { (n - row_mismatch) / 2 }
} else {
row_mismatch.min(n - row_mismatch) / 2
};
let col_swaps = if n % 2 == 1 {
if col_mismatch % 2 == 0 { col_mismatch / 2 } else { (n - col_mismatch) / 2 }
} else {
col_mismatch.min(n - col_mismatch) / 2
};
(row_swaps + col_swaps) as i32
}
}