Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 80201b8

Browse files
committedMar 14, 2025
Add solution #782
1 parent 5cceb5c commit 80201b8

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,7 @@
592592
779|[K-th Symbol in Grammar](./0779-k-th-symbol-in-grammar.js)|Medium|
593593
780|[Reaching Points](./0780-reaching-points.js)|Hard|
594594
781|[Rabbits in Forest](./0781-rabbits-in-forest.js)|Medium|
595+
782|[Transform to Chessboard](./0782-transform-to-chessboard.js)|Hard|
595596
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
596597
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
597598
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)
Please sign in to comment.