|
| 1 | +/** |
| 2 | + * 782. Transform to Chessboard |
| 3 | + * https://leetcode.com/problems/transform-to-chessboard/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an n x n binary grid board. In each move, you can swap any two rows with each |
| 7 | + * other, or any two columns with each other. |
| 8 | + * |
| 9 | + * Return the minimum number of moves to transform the board into a chessboard board. If the |
| 10 | + * task is impossible, return -1. |
| 11 | + * |
| 12 | + * A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[][]} board |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var movesToChessboard = function(board) { |
| 20 | + const n = board.length; |
| 21 | + |
| 22 | + for (let i = 0; i < n; i++) { |
| 23 | + for (let j = 0; j < n; j++) { |
| 24 | + if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) === 1) { |
| 25 | + return -1; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + let rowSum = 0; |
| 31 | + let colSum = 0; |
| 32 | + let rowSwaps = 0; |
| 33 | + let colSwaps = 0; |
| 34 | + |
| 35 | + for (let i = 0; i < n; i++) { |
| 36 | + rowSum += board[0][i]; |
| 37 | + colSum += board[i][0]; |
| 38 | + |
| 39 | + if (board[i][0] === i % 2) rowSwaps++; |
| 40 | + if (board[0][i] === i % 2) colSwaps++; |
| 41 | + } |
| 42 | + |
| 43 | + if (rowSum !== Math.floor(n / 2) && rowSum !== Math.ceil(n / 2)) return -1; |
| 44 | + if (colSum !== Math.floor(n / 2) && colSum !== Math.ceil(n / 2)) return -1; |
| 45 | + |
| 46 | + if (n % 2 === 1) { |
| 47 | + if (rowSwaps % 2 === 1) rowSwaps = n - rowSwaps; |
| 48 | + if (colSwaps % 2 === 1) colSwaps = n - colSwaps; |
| 49 | + } else { |
| 50 | + rowSwaps = Math.min(rowSwaps, n - rowSwaps); |
| 51 | + colSwaps = Math.min(colSwaps, n - colSwaps); |
| 52 | + } |
| 53 | + |
| 54 | + return Math.floor((rowSwaps + colSwaps) / 2); |
| 55 | +}; |
0 commit comments