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.
For example:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j]
is either 0
or 1
.class Solution:
def largestIsland(self, grid: list[list[int]]) -> int:
n = len(grid)
def dfs(i, j, island_id):
if i < 0 or i >= n or j < 0 or j >= n or grid[i][j] != 1:
return 0
grid[i][j] = island_id
size = 1
size += dfs(i + 1, j, island_id)
size += dfs(i - 1, j, island_id)
size += dfs(i, j + 1, island_id)
size += dfs(i, j - 1, island_id)
return size
island_sizes = {}
island_id = 2
max_island = 0
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
size = dfs(i, j, island_id)
island_sizes[island_id] = size
max_island = max(max_island, size)
island_id += 1
max_island_after_flip = max_island
for i in range(n):
for j in range(n):
if grid[i][j] == 0:
neighbors = set()
if i > 0:
neighbors.add(grid[i - 1][j])
if i < n - 1:
neighbors.add(grid[i + 1][j])
if j > 0:
neighbors.add(grid[i][j - 1])
if j < n - 1:
neighbors.add(grid[i][j + 1])
total_size = 1
for neighbor in neighbors:
if neighbor > 1:
total_size += island_sizes[neighbor]
max_island_after_flip = max(max_island_after_flip, total_size)
return max_island_after_flip
The naive approach would be to iterate through each 0
in the grid, temporarily change it to 1
, and then calculate the size of the resulting island using Depth-First Search (DFS) or Breadth-First Search (BFS). We keep track of the maximum island size found so far. After processing each 0
, we revert it back to 0
to maintain the original grid.
The optimal approach aims to avoid redundant DFS/BFS calculations for connected components. The steps are as follows:
0
in the grid. For each 0
, check its 4-directional neighbors. If the neighbors are part of an island (i.e., have an island ID), add their sizes to calculate the potential island size if the 0
is flipped to 1
. Use a set to keep track of visited island IDs to avoid double-counting.0
, we check its 4 neighbors, which takes O(1) time. Thus, this step takes O(n^2) time.Therefore, the overall time complexity is O(n^2).
1
in the grid forms its own island. Therefore, the dictionary can store up to O(n^2) island sizes.1
s).Therefore, the overall space complexity is O(n^2).