-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCandy Crush.java
58 lines (52 loc) · 2.08 KB
/
Candy Crush.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
int m, n;
public int[][] candyCrush(int[][] board) {
m = board.length;
n = board[0].length;
Set<int[]> reset = check(board);
if(reset.isEmpty()) return board;
board = collapse(board, reset);
return candyCrush(board);
}
public Set<int[]> check(int[][] board) {
//search crush positions
Set<int[]> reset = new HashSet<>();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
// skip all 0s!!
if(board[i][j] == 0) continue;
// check 4 directions, 2 steps on one side or 1 step on both sides
if(i > 1 && board[i-1][j] == board[i][j] && board[i-2][j] == board[i][j] ||
i < m-2 && board[i+1][j] == board[i][j] && board[i+2][j] == board[i][j] ||
i > 0 && board[i-1][j] == board[i][j] && i < m-1 && board[i+1][j] == board[i][j] ||
j > 1 && board[i][j-1] == board[i][j] && board[i][j-2] == board[i][j] ||
j < n-2 && board[i][j+1] == board[i][j] && board[i][j+2] == board[i][j] ||
j > 0 && board[i][j-1] == board[i][j] && j < n-1 && board[i][j+1] == board[i][j]) {
reset.add(new int[] {i, j});
}
}
}
return reset;
}
public int[][] collapse(int[][] board, Set<int[]> reset) {
// set value to 0
for(int[] pos: reset) board[pos[0]][pos[1]] = 0;
// collapse empty spaces, 2ptrs, col by col
for(int j = 0; j < n; j++) {
int top = m-1, bot = m-1;
while(top >= 0) {
if(board[top][j] == 0) top--;
else {
board[bot][j] = board[top][j];
bot--;
top--;
}
}
while(bot >= 0) {
board[bot][j] = 0;
bot--;
}
}
return board;
}
}