Problem Description
Given an n x n binary matrix, you can change at most one 0 to 1. After changing a single 0, return the size of the largest possible island created by connecting adjacent 1s (using 4-directional connections).
Key Insights
- First, identify and label every existing island using DFS/BFS.
- Maintain a mapping from island id to its size.
- For each 0, examine its four neighbors. Sum the size of distinct adjacent islands and add 1 (for the flipped cell) to compute a candidate island size.
- Be careful to avoid counting the same island more than once when summing.
- If the grid is full of 1s (i.e. no 0 to flip), then the largest island is the whole grid.
Space and Time Complexity
Time Complexity: O(n^2) because each cell is visited a constant number of times. Space Complexity: O(n^2) for the recursion/queue in DFS/BFS in the worst case and for storing island information.
Solution
The solution uses a two-phase algorithm. In the first phase, we use DFS to label each island with a unique id (starting from 2 to avoid confusion with 0 and 1) and record its area in a mapping (dictionary). In the second phase, for each cell that is 0, we look at its 4-directional neighbors to find distinct islands. We then sum the sizes of these islands and add 1 (for converting the current 0 into a 1), tracking the maximum island size possible. This approach efficiently calculates the largest island that can be created after a single modification.