Bricks Falling When Hit - Problem

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 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 (i.e., 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 ith erasure is applied.

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

Input & Output

Example 1 — Basic Hit
$ Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
Output: [2]
💡 Note: Initially all 4 bricks are stable. After hitting (1,0), only the top-left brick remains stable, so 2 bricks fall (the ones at (1,1) and (1,2)).
Example 2 — Multiple Hits
$ Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
Output: [0,1]
💡 Note: First hit at (1,1) removes an isolated brick, no others fall. Second hit at (1,0) disconnects the remaining bottom brick from the top, so 1 brick falls.
Example 3 — Empty Hit
$ Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,3]]
Output: [0]
💡 Note: Hitting position (1,3) which has no brick, so no bricks fall.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 200
  • grid[i][j] is 0 or 1
  • 1 ≤ hits.length ≤ 4 × 104
  • hits[i].length == 2
  • 0 ≤ xi ≤ m - 1
  • 0 ≤ yi ≤ n - 1

Visualization

Tap to expand
Bricks Falling When Hit: Stability AnalysisInput: Grid + Hits1111Hit: (1,0)Process: Check StabilityCeilingXHit??Output: Fallen Count1fellfellfellResult: [2]Key Insight: Bricks are stable if connected to ceiling through chain of stable neighborsWhen we remove the supporting brick at (1,0), bricks (1,1) and (1,2) lose their connectionEfficient solution: Use Union-Find working backwards from final stateAdd bricks back instead of removing them to avoid repeated connectivity checks
Understanding the Visualization
1
Initial Grid
Grid with stable bricks (connected to top or stable neighbors)
2
Apply Hit
Remove brick at specified position
3
Count Fallen
Count bricks that lose all connections to the ceiling
Key Takeaway
🎯 Key Insight: Work backwards with Union-Find to efficiently track ceiling connectivity instead of repeatedly checking after each removal
Asked in
Google 35 Facebook 28 Amazon 22
28.0K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen