Problem Description
Given an m x n grid with bricks (1 represents a brick, 0 represents an empty space), a brick is considered stable if it is connected directly to the top row or connected (vertically or horizontally) to another stable brick. We are given an array of hit operations (each hit erases a possible brick). After each hit, some bricks may lose connectivity and fall (i.e. be removed). The problem asks to return an array where each element is the number of bricks that fall as a result of the corresponding hit.
Key Insights
- Instead of processing hits in the forward order (which leads to complex dependency chains), process the hits in reverse order.
- Remove all bricks corresponding to hits initially and build the connected components (using Union Find) for the remaining grid.
- Introduce a special "roof" node to represent the stability provided by the top row.
- In the reverse process, restore one brick at a time and union it with adjacent bricks. The increase in the number of bricks connected to the roof indicates how many bricks become stable.
- The brick being restored is not counted as "fallen" so subtract one from the increase.
Space and Time Complexity
Time Complexity: O(mn + k * α(mn)) where mn is the size of the grid, k is the number of hits, and α is the inverse Ackermann function (almost constant). Space Complexity: O(mn) for the Union Find data structure and auxiliary arrays.
Solution
We solve this problem by using a Union Find (Disjoint Set Union) data structure with a twist. First, we simulate all hits by marking the bricks as removed. Then, we build the union structure for the remaining grid while uniting adjacent bricks. A virtual roof node is used to represent stability from the top row. After the initial setup, we process hits in reverse order. For every hit that originally removed a brick, we add the brick back and connect it to its neighbors if they exist. By checking the difference in the size of the connected component at the roof node before and after the restoration, we determine how many bricks become stable due to this brick and hence would not have fallen if the hit had not occurred. Since the brick we restore should not be counted, we subtract one from that difference. This reverse approach transforms the problem into several union operations and gives an efficient solution.