Bricks Falling When Hit

You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:

  • It is directly connected to the top of the grid, or
  • At least one other brick in its four adjacent cells is stable.

You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location, if it exists, will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid, meaning it does not land on other stable bricks.

Return an array result, where each result[i] is the number of bricks that will fall after the i^th erasure is applied.

Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.

Example 1
1 0 0 0
1 1 1 0
Inputgrid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
Output[2]
After erasing the brick at (1,0), the two remaining bottom-row bricks are no longer stable and fall, so the result is [2].
Example 2
1 0 0 0
1 1 0 0
Inputgrid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
Output[0,0]
Erasing (1,1) and then (1,0) causes no additional bricks to fall because all remaining bricks after each erasure are stable.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • grid[i][j] is 0 or 1.
  • 1 <= hits.length <= 4 * 10^4
  • hits[i].length == 2
  • 0 <= xi <= m - 1
  • 0 <= yi <= n - 1
  • All (xi, yi) are unique.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate