Problem Description
Given an initially water-filled m x n grid, you perform a sequence of add-land operations at specified positions. After each operation, return the number of islands present. An island is defined as a group of adjacent lands connected horizontally or vertically.
Key Insights
- Use Union Find (Disjoint Set Union) to efficiently manage connected components (islands).
- Map 2D grid coordinates to a 1D index.
- When adding a new land, check its 4 neighbors (up, down, left, right) and perform unions if they are also lands.
- Avoid duplicate processing if the same cell is added multiple times.
- Maintain a counter for islands that is updated during each union operation.
Space and Time Complexity
Time Complexity: O(K * α(mn)) where K is the number of operations and α is the inverse Ackermann function (almost constant time per union/find). Space Complexity: O(mn) for storing the union-find structure.
Solution
The solution relies on the Union Find data structure to dynamically merge islands. When a new land cell is added:
- If the cell is already land, record the current island count.
- Otherwise, mark the cell as land and increment the island count.
- Check the four neighboring cells; if any neighbor is land, attempt to union the current cell with that neighbor.
- If a union actually happens (i.e., the two cells were in separate islands), decrement the island counter.
- Output the island count after each add-land operation. The key trick is converting 2D indices to a 1D representation (r * n + c) and using path compression along with union by rank in the Union Find implementation for optimal performance.