Bricks Falling When Hit LeetCode solution in Java

1
class Solution {
2
int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
3

4
public int[] hitBricks(int[][] grid, int[][] hits) {
5
// marking all the hits that has a brick with -1
6
for (int i = 0; i < hits.length; i++)
7
if (grid[hits[i][0]][hits[i][1]] == 1) grid[hits[i][0]][hits[i][1]] = -1;
8

9
// marking all the stable bricks
10
for (int i = 0; i < grid[0].length; i++) markAndCountStableBricks(grid, 0, i);
11

12
int[] res = new int[hits.length];
13
// looping over hits array backwards and restoring bricks
14
for (int i = hits.length - 1; i >= 0; i--) {
15
int row = hits[i][0];
16
int col = hits[i][1];
17

18
// hit is at empty space so continue
19
if (grid[row][col] == 0) continue;
20

21
// marking it with 1, this signifies that a brick is present in an unstable state and will be
22
// restored in the future
23
grid[row][col] = 1;
24
// checking brick stability, if it's unstable no need to visit the neighbours
25
if (!isStable(grid, row, col)) continue;
26

27
// So now as our brick is stable we can restore all the bricks connected to it
28
// mark all the unstable bricks as stable and get the count
29
res[i] =
30
markAndCountStableBricks(grid, hits[i][0], hits[i][1])
31
- 1; // Subtracting 1 from the total count, as we don't wanna include the starting
32
// restored brick
33
}
34

35
return res;
36
}
37

38
private int markAndCountStableBricks(int[][] grid, int row, int col) {
39
if (grid[row][col] == 0 || grid[row][col] == -1) return 0;
40

41
grid[row][col] = 2;
42
int stableBricks = 1;
43
for (int[] dir : dirs) {
44
int r = row + dir[0];
45
int c = col + dir[1];
46

47
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue;
48

49
if (grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2) continue;
50

51
stableBricks += markAndCountStableBricks(grid, r, c);
52
}
53

54
return stableBricks;
55
}
56

57
private boolean isStable(int[][] grid, int row, int col) {
58
if (row == 0) return true;
59

60
for (int[] dir : dirs) {
61
int r = row + dir[0];
62
int c = col + dir[1];
63

64
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue;
65

66
if (grid[r][c] == 2) return true;
67
}
68

69
return false;
70
}
71
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0