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 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
(i.e., it does not land on other stable bricks).
Return an arrayresult
, where eachresult[i]
_is the number of bricks that willfall after the _ith
erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
Examples
Example 1
|
|
Example 2
|
|
Constraints
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[i][j]
is0
or1
.1 <= hits.length <= 4 * 10^4
hits[i].length == 2
0 <= xi <= m - 1
0 <= yi <= n - 1
- All
(xi, yi)
are unique.
Solution
Method 1 – Reverse Union-Find (Disjoint Set Union)
Intuition
Instead of simulating each hit forward, we process the hits in reverse. We first remove all bricks that will be hit, then add them back one by one, using Union-Find to track which bricks are connected to the top. The difference in the number of stable bricks before and after each addition gives the number of bricks that fall.
Approach
- Copy the grid and remove all bricks at hit positions.
- Use Union-Find to connect all remaining bricks, and connect bricks in the top row to a virtual top node.
- Process hits in reverse:
- If the hit was on a brick, add it back.
- Union it with its neighbors if they are bricks.
- If it is in the top row, union it with the virtual top.
- The number of new bricks connected to the top (excluding the added one) is the answer for this hit.
- Return the result in the original order.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m*n + q*α(m*n))
where q = len(hits), α is the inverse Ackermann function. - 🧺 Space complexity:
O(m*n)
— For the union-find structure and grid copy.