-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
candy-crush.cpp
48 lines (42 loc) · 1.52 KB
/
candy-crush.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
// Time: O((R * C)^2)
// Space: O(1)
class Solution {
public:
vector<vector<int>> candyCrush(vector<vector<int>>& board) {
const auto R = board.size(), C = board[0].size();
bool changed = true;
while (changed) {
changed = false;
for (int r = 0; r < R; ++r) {
for (int c = 0; c + 2 < C; ++c) {
auto v = abs(board[r][c]);
if (v != 0 && v == abs(board[r][c + 1]) && v == abs(board[r][c + 2])) {
board[r][c] = board[r][c + 1] = board[r][c + 2] = -v;
changed = true;
}
}
}
for (int r = 0; r + 2 < R; ++r) {
for (int c = 0; c < C; ++c) {
auto v = abs(board[r][c]);
if (v != 0 && v == abs(board[r + 1][c]) && v == abs(board[r + 2][c])) {
board[r][c] = board[r + 1][c] = board[r + 2][c] = -v;
changed = true;
}
}
}
for (int c = 0; c < C; ++c) {
int empty_r = R - 1;
for (int r = R - 1; r >= 0; --r) {
if (board[r][c] > 0) {
board[empty_r--][c] = board[r][c];
}
}
for (int r = empty_r; r >= 0; --r) {
board[r][c] = 0;
}
}
}
return board;
}
};