782. Transform to Chessboard
Description
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
or1
.
Solutions
Solution: Math
- Time complexity: O(n2)
- Space complexity: O(1)
JavaScript
js
/**
* @param {number[][]} board
* @return {number}
*/
const movesToChessboard = function (board) {
const n = board.length;
for (let row = 0; row < n; row++) {
for (let col = 0; col < n; col++) {
const topLeft = board[0][0];
const topRight = board[0][col];
const bottomLeft = board[row][0];
const bottomRight = board[row][col];
// 0 or 1 only has an odd count is invalid
if (topLeft ^ topRight ^ bottomLeft ^ bottomRight) return -1;
}
}
let colSum = (rowSum = colMisplace = rowMisplace = 0);
for (let index = 0; index < n; index++) {
colSum += board[index][0];
rowSum += board[0][index];
// target to 01010...
if (board[index][0] !== index % 2) colMisplace += 1;
if (board[0][index] !== index % 2) rowMisplace += 1;
}
if (colSum !== Math.floor(n / 2) && colSum !== Math.floor((n + 1) / 2)) return -1;
if (rowSum !== Math.floor(n / 2) && rowSum !== Math.floor((n + 1) / 2)) return -1;
if (n % 2) {
if (colMisplace % 2) colMisplace = n - colMisplace;
if (rowMisplace % 2) rowMisplace = n - rowMisplace;
} else {
colMisplace = Math.min(n - colMisplace, colMisplace);
rowMisplace = Math.min(n - rowMisplace, rowMisplace);
}
return (colMisplace + rowMisplace) / 2;
};