Largest Land Mass After One Water-to-Land Conversion
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests grid connected-component labeling and the ability to optimally merge adjacent island regions by flipping a single water cell to land.
You are given an n × n binary grid where 1 represents land and 0 represents water. Cells are connected in four cardinal directions (up, down, left, right); diagonal adjacency does not count.
You may convert at most one water cell (0) into a land cell (1). Return the size of the largest possible land mass (connected component of 1s) after this optional conversion.
If converting a water cell causes previously separate islands to touch, they merge into a single land mass through the converted cell.
Rules and Edge Cases
- You are not required to flip any cell. If every cell is already land, return the size of the existing land mass.
- If no land exists at all, flipping any single water cell produces a land mass of size
1, so return1. - If the grid is empty, return
0. - When a water cell borders the same island from multiple sides (for example, a U-shaped island wrapping around a gap), that island's size must be counted only once in the merged total.
Constraints
1 ≤ n ≤ 1000grid[i][j]is either0or1- The grid is square (
nrows andncolumns) - Your solution must run in O(n²) time and use O(n²) or better space
- Do not use recursive depth-first search on large grids; Python's default call stack will overflow on grids up to
n = 1000
Examples
Example 1
Input: max_island_one_conversion([[1, 0], [0, 1]])
Output: 3
Example 2
Input: max_island_one_conversion([[1, 1], [1, 0]])
Output: 4
Example 3
Input: max_island_one_conversion([[0, 0], [0, 0]])
Output: 1
Example 4
Input: max_island_one_conversion([[1, 1], [1, 1]])
Output: 4
Hints
Hint 1
In a first pass, assign every island a unique integer ID and record how many cells each island contains. A cell value of 0 stays unlabeled (ID 0).
Hint 2
For each water cell, gather the IDs of all labeled neighbors into a set — not a list — before summing their sizes. The set prevents counting the same island twice when it wraps around the water cell.
Hint 3
Track the largest island found during labeling. That value is your answer when no flip improves things (or when there are no water cells at all), so initialize your running best to it before scanning water cells.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core observation is that flipping a single water cell at position z can only affect islands that are directly adjacent to z. Any two land regions that do not border z remain disconnected regardless of what happens at z. So the new land mass containing z has exactly one size: 1 (for z itself) plus the total cells in every distinct island that touches z.
This motivates a clean two-pass algorithm.
Pass 1 — Label connected components
Walk every cell. When an unlabeled land cell is found, assign it the next available integer label and flood-fill the whole island using an explicit stack (not recursion, to avoid Python stack overflow on large grids). Mark each cell as it is pushed so it is never pushed twice. At the end of each fill, store the island's size in a list indexed by label.
Keep a running best equal to the largest island found. This handles two edge cases at once: a grid with no water cells (no flip is possible, so the original best is the answer), and a flip that turns out to be useless.
Pass 2 — Score every water cell
For each water cell, look at its up to four neighbors and collect their island labels into a set. The set is essential: a U-shaped island can touch the same water cell from two or more sides, and counting it twice would overcount. Sum the sizes of every label in the set, add 1 for the converted cell itself, and update best.
Why this is correct
Flipping z merges exactly the islands adjacent to z into one component through z. Any island not adjacent to z is unaffected. The size of the merged component is therefore 1 + Σ(sizes of distinct neighboring islands). We evaluate this for every candidate water cell and take the maximum, so no option is missed.
Edge cases
- All water: no islands are labeled. Every water cell scores
1. Answer is1. - All land: no water cell is visited in pass 2.
bestfrom pass 1 equalsn². - Empty grid: caught by the early return of
0. - U-shaped island: the set in pass 2 deduplicates the label, preventing double-counting.
Complexity
- Time: O(n²). Each cell is pushed onto the stack at most once in pass 1 (marked on push), and each cell checks exactly 4 neighbors in both passes.
- Space: O(n²) for the label grid and the stack; O(number of islands) ≤ O(n²) for the sizes list.
Reference solution
from typing import List
def max_island_one_conversion(grid: List[List[int]]) -> int:
n = len(grid)
if n == 0:
return 0
# island_id[r][c] = 0 means water or unlabeled; positive int = island label
island_id = [[0] * n for _ in range(n)]
sizes = [0] # sizes[0] is a placeholder so real labels start at 1
best = 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
# Pass 1: label every land cell with its island ID and record island sizes
for r in range(n):
for c in range(n):
if grid[r][c] != 1 or island_id[r][c] != 0:
continue
label = len(sizes)
stack = [(r, c)]
island_id[r][c] = label
size = 0
while stack:
x, y = stack.pop()
size += 1
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n:
if grid[nx][ny] == 1 and island_id[nx][ny] == 0:
island_id[nx][ny] = label
stack.append((nx, ny))
sizes.append(size)
if size > best:
best = size
# Pass 2: for every water cell, compute the merged size if it were flipped
for r in range(n):
for c in range(n):
if grid[r][c] != 0:
continue
# Use a set so a U-shaped island bordering this cell isn't double-counted
adjacent_labels = set()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
lbl = island_id[nr][nc]
if lbl != 0:
adjacent_labels.add(lbl)
candidate = 1 # the converted cell itself
for lbl in adjacent_labels:
candidate += sizes[lbl]
if candidate > best:
best = candidate
return best