2
int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};4
public int[] hitBricks(int[][] grid, int[][] hits) {5
// marking all the hits that has a brick with -16
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;9
// marking all the stable bricks10
for (int i = 0; i < grid[0].length; i++) markAndCountStableBricks(grid, 0, i);12
int[] res = new int[hits.length];13
// looping over hits array backwards and restoring bricks14
for (int i = hits.length - 1; i >= 0; i--) {18
// hit is at empty space so continue19
if (grid[row][col] == 0) continue;21
// marking it with 1, this signifies that a brick is present in an unstable state and will be22
// restored in the future24
// checking brick stability, if it's unstable no need to visit the neighbours25
if (!isStable(grid, row, col)) continue;27
// So now as our brick is stable we can restore all the bricks connected to it28
// mark all the unstable bricks as stable and get the count30
markAndCountStableBricks(grid, hits[i][0], hits[i][1])31
- 1; // Subtracting 1 from the total count, as we don't wanna include the starting38
private int markAndCountStableBricks(int[][] grid, int row, int col) {39
if (grid[row][col] == 0 || grid[row][col] == -1) return 0;43
for (int[] dir : dirs) {47
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue;49
if (grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2) continue;51
stableBricks += markAndCountStableBricks(grid, r, c);57
private boolean isStable(int[][] grid, int row, int col) {58
if (row == 0) return true;60
for (int[] dir : dirs) {64
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue;66
if (grid[r][c] == 2) return true;