Bricks Falling When Hit
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Bricks Falling When Hit
You are given an binary grid where
1 represents a brick. A brick will not fall if it is connected to the top row (row index 0) or another brick that will not fall. When a brick is 'hit', it turns into 0. Return the number of bricks that fall after each hit.Reverse Union-Find Strategy
- Remove all hit bricks first.
- Build the initial graph for the remaining bricks.
- Add hit bricks back in reverse order.
- The number of new bricks connected to the top row (excluding the re-added brick itself) is the number of falling bricks for that hit.
Examples
Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
Output: [2]
Approach 1
Level II: BFS (Exhaustive Simulation)
Intuition
This approach directly simulates the process for each hit. After removing a brick, we perform a broad connectivity check (using BFS/DFS) to see which bricks are still connected to the top row. Any brick that was previously connected but is no longer is counted as 'fallen'.
⏱ O(K \cdot M \cdot N) where K is number of hits.💾 O(M \cdot N).
Approach 2
Level III: Reverse DSU (Connectivity Recovery)
Intuition
Tracking 'falling' bricks is hard. Tracking 'recovered' bricks by adding them back in reverse is much easier. Use a dummy node to represent the 'ceiling' (connected to all row 0 bricks).
⏱ O((H + M*N) * alpha(M*N)) where H is hits.💾 O(M*N).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.