forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTransform to Chessboard.cpp
54 lines (40 loc) · 1.59 KB
/
Transform to Chessboard.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
int movesToChessboard(vector<vector<int>>& board) {
int N = board.size();
int colMovesNeeded = 0, rowMovesNeeded = 0;
int onesInFirstCol = 0, onesInFirstRow = 0;
int zerosInFirstCol = 0, zerosInFirstRow = 0;
for (int i=1; i<board.size(); i++) {
for (int j=1; j<board[i].size(); j++) {
if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {
return -1;
}
}
}
for (int i=0; i<N; i++) {
if (board[0][i]) onesInFirstRow++;
else zerosInFirstRow++;
if (board[i][0]) onesInFirstCol++;
else zerosInFirstCol++;
}
if (abs(onesInFirstRow - zerosInFirstRow) > 1) return -1;
if (abs(onesInFirstCol - zerosInFirstCol) > 1) return -1;
for (int i=0; i<N; i++) {
if (board[0][i] == i%2) rowMovesNeeded++;
if (board[i][0] == i%2) colMovesNeeded++;
}
if (N % 2 == 1) {
if (onesInFirstCol < zerosInFirstCol) {
colMovesNeeded = N - colMovesNeeded;
}
if (onesInFirstRow < zerosInFirstRow) {
rowMovesNeeded = N - rowMovesNeeded;
}
} else {
colMovesNeeded = min(colMovesNeeded, N-colMovesNeeded);
rowMovesNeeded = min(rowMovesNeeded, N-rowMovesNeeded);
}
return (colMovesNeeded + rowMovesNeeded) / 2;
}
};