forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTransform to Chessboard.java
42 lines (41 loc) · 1.31 KB
/
Transform to Chessboard.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public int movesToChessboard(int[][] board) {
int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {
return -1;
}
}
}
for (int i = 0; i < N; i++) {
rowOneCnt += board[0][i];
colOneCnt += board[i][0];
if (board[i][0] == i % 2) {
rowToMove++;
}
if (board[0][i] == i % 2) {
colToMove++;
}
}
if (rowOneCnt < N / 2 || rowOneCnt > (N + 1) / 2) {
return -1;
}
if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {
return -1;
}
if (N % 2 == 1) {
// we cannot make it when ..ToMove is odd
if (colToMove % 2 == 1) {
colToMove = N - colToMove;
}
if (rowToMove % 2 == 1) {
rowToMove = N - rowToMove;
}
} else {
colToMove = Math.min(colToMove, N - colToMove);
rowToMove = Math.min(rowToMove, N - rowToMove);
}
return (colToMove + rowToMove) / 2;
}
}