-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformtoChessboard.cpp
More file actions
39 lines (38 loc) · 1.21 KB
/
transformtoChessboard.cpp
File metadata and controls
39 lines (38 loc) · 1.21 KB
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
// Source: https://leetcode.com/problems/transform-to-chessboard/
// Author: Miao Zhang
// Date: 2021-03-10
class Solution {
public:
int movesToChessboard(vector<vector<int>>& board) {
int n = board.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((board[0][0] ^ board[0][j] ^ board[i][0] ^ board[i][j]) == 1) return -1;
}
}
int row = 0, col = 0;
int cntrow = 0, cntcol = 0;
for (int i = 0; i < n; i++) {
row += board[0][i];
col += board[i][0];
if (board[0][i] != i % 2) cntrow++; // 0101010...
if (board[i][0] != i % 2) cntcol++; // 0101010...
}
if (row < n / 2 || row > (n + 1) / 2) return -1;
if (col < n / 2 || col > (n + 1) / 2) return -1;
int res = 0;
if (n % 2 == 0) {
res += min(cntrow, n - cntrow);
res += min(cntcol, n - cntcol);
} else {
if (cntrow % 2 == 1) {
cntrow = n - cntrow;
}
if (cntcol % 2 == 1) {
cntcol = n - cntcol;
}
res = cntrow + cntcol;
}
return res / 2;
}
};