Problem
You are given an n x n
binary matrix grid
. You are allowed to change at most one 0
to be 1
.
Return the size of the largest island in grid
after applying this operation.
An island is a 4-directionally connected group of 1
s.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j]
is either0
or1
.
Solution
Method 1 - Using DFS + Hashing
This problem will be similar to Number of Islands. Here is the approach:
- Identify Islands: Traverse the grid to find and label all existing islands. Use DFS or BFS to calculate the size of each island. Store each island’s size in a dictionary.
- Track Connectivity: Use a parent array to track the root of each cell in every island. Also, mark cells (
0
s) that, when flipped to1
, can connect two or more islands. - Simulate Flipping: For each
0
, calculate the potential island size if that0
is flipped to1
by summing the sizes of all unique islands it would connect. - Calculate the Largest Island: Compare the size of the islands after each possible flip to find the maximum size.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, since we potentially traverse the entire grid multiple times. - 🧺 Space complexity:
O(n^2)
, for storing island labels and sizes.