-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path723.cpp
More file actions
62 lines (61 loc) · 1.88 KB
/
723.cpp
File metadata and controls
62 lines (61 loc) · 1.88 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
public:
int M;
int N;
void moveDown(vector<vector<int>>& board) {
for (int j = 0; j < N; ++j) {
int slow = M - 1;
for (int i = M - 1; i >= 0; --i) {
if (board[i][j] != 0) {
board[slow][j] = board[i][j];
slow--;
}
}
for (; slow >= 0; slow--) board[slow][j] = 0;
}
}
bool extend(vector<vector<int>>& board, int x, int y) {
bool isComplete = true;
int num = abs(board[x][y]);
// check down
int down = x;
while (down + 1 < M && abs(board[down + 1][y]) == num) down++;
if (down - x + 1 >= 3) {
isComplete = false;
for (int i = x; i <= down; ++i) board[i][y] = -abs(board[i][y]);
}
// check right
int right = y;
while (right + 1 < N && abs(board[x][right + 1]) == num) right++;
if (right - y + 1 >= 3) {
isComplete = false;
for (int j = y; j <= right; ++j) board[x][j] = -abs(board[x][j]);
}
return isComplete;
}
bool crash(vector<vector<int>>& board) {
bool isComplete = true;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (board[i][j] == 0) continue;
if (!extend(board, i, j)) isComplete = false;
}
}
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (board[i][j] < 0) board[i][j] = 0;
}
}
return isComplete;
}
vector<vector<int>> candyCrush(vector<vector<int>>& board) {
M = board.size();
N = board[0].size();
bool isComplete = false;
while (!isComplete) {
isComplete = crash(board);
moveDown(board);
}
return board;
}
};