Best Plot After Reclaiming a Single Water Tile
Trees & GraphsAuto-graded · 24 test casesLast updated
Find the largest connected land region achievable by turning at most one water cell into land, which tests component labeling and merging neighbors without double counting.
Best Plot After Reclaiming a Single Water Tile
A map is stored as a rectangular grid of integers. A 1 is a land tile and a 0 is a water tile. Land tiles that are adjacent horizontally or vertically belong to the same landmass. Tiles that touch only at a corner are not connected.
You may reclaim at most one water tile, turning it into land. You may also choose to reclaim nothing. Return the number of tiles in the largest landmass that can exist after your choice.
Details
- The size of a landmass is the number of tiles it contains.
- If the grid contains no water, the answer is simply the total number of tiles.
- If the grid contains no land, reclaiming any one tile gives a landmass of size 1.
- Reclaiming a water tile merges it with every landmass that is directly adjacent (up, down, left, right). If the same landmass touches the tile on several sides, its tiles are counted only once.
Function
Implement biggest_landmass_with_one_reclaim(grid), where grid is a list of rows, each a list of 0/1 integers. Return a single integer: the largest possible landmass size.
Constraints
1 <= len(grid) <= 5001 <= len(grid[i]) <= 500, and all rows have the same length- Every
grid[i][j]is0or1 - The answer is at most
250000
Examples
Example 1
Input: biggest_landmass_with_one_reclaim([[1, 0], [0, 1]])
Output: 3
Example 2
Input: biggest_landmass_with_one_reclaim([[1, 1], [1, 1]])
Output: 4
Example 3
Input: biggest_landmass_with_one_reclaim([[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 1, 1]])
Output: 5
Hints
Hint 1
Reclaiming a water tile never changes the existing landmasses by itself; it only joins the ones next to it. So you can compute landmass sizes once and reuse them.
Hint 2
Label each landmass with an id and store its size. Then, for each water tile, look at its four neighbors and gather the ids.
Hint 3
A water tile may touch the same landmass on more than one side. Add each distinct id's size only once, plus 1 for the reclaimed tile itself. Do not forget the answer when no change is made, and avoid deep recursion on large grids.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Trying every water tile and re-scanning the whole grid would cost O((R·C)^2), far too slow for a 500 by 500 grid. The key observation is that reclaiming a tile does not alter existing landmasses; it only joins those adjacent to it. So the work splits into two passes:
- Label landmasses. Flood-fill each landmass once, assign it an id, and record its size.
- Score each water tile. Look at its four neighbors, collect the distinct landmass ids, and compute
1 + sum of those landmass sizes.
The answer is the maximum of all these scores and the largest existing landmass (which covers the "change nothing" option).
Implementation notes
- The grid is copied into a flat array with a one-tile border, so neighbors are at offsets
±1and±Wwith no bounds checks. Border and water cells hold-1, unlabeled land holds0, and labeled land holds its positive id. - An explicit stack is used instead of recursion, since a single landmass can have up to 250,000 tiles.
- A tile is labeled when it is pushed, so it is never pushed twice.
- With at most four neighbor ids, duplicates are removed by comparing against the earlier ids instead of building a set.
Why it is correct
- Each flood fill reaches exactly the tiles 4-connected to its start, so every landmass gets one id and the stored sizes are exact.
- After reclaiming tile
w, its landmass consists ofwplus every landmass with a tile adjacent tow. These landmasses are disjoint, so their sizes add, provided each is counted once. - Landmasses not touching
wkeep their sizes, and none exceeds the initial maximum, which is already included inbest.
Edge cases
- No water: no tile is scored, and the answer is the largest landmass, i.e. R·C.
- No land: every water tile scores 1, so the answer is 1.
- A landmass touching a water tile on several sides is counted once.
- Diagonal neighbors are ignored.
Complexity
- Time: O(R·C), since each tile is visited a constant number of times.
- Space: O(R·C) for the label array, stack, and size list.
Reference solution
from typing import List
def biggest_landmass_with_one_reclaim(grid: List[List[int]]) -> int:
R = len(grid)
C = len(grid[0])
W = C + 2
# Padded flat grid: -1 = water/border, 0 = unlabeled land, >0 = landmass id
lab = [-1] * ((R + 2) * W)
for r in range(R):
row = grid[r]
base = (r + 1) * W + 1
for c in range(C):
if row[c]:
lab[base + c] = 0
sizes = [0] # sizes[0] is a placeholder; ids start at 1
steps = (1, -1, W, -W)
for p in range((R + 2) * W):
if lab[p] != 0:
continue
cur = len(sizes)
lab[p] = cur
stack = [p]
cnt = 0
while stack:
x = stack.pop()
cnt += 1
for d in steps:
y = x + d
if lab[y] == 0:
lab[y] = cur
stack.append(y)
sizes.append(cnt)
best = max(sizes) # option: change nothing
for r in range(R):
row = grid[r]
base = (r + 1) * W + 1
for c in range(C):
if row[c]:
continue
p = base + c
a = lab[p - 1]
b = lab[p + 1]
u = lab[p - W]
v = lab[p + W]
s = 1
if a > 0:
s += sizes[a]
if b > 0 and b != a:
s += sizes[b]
if u > 0 and u != a and u != b:
s += sizes[u]
if v > 0 and v != a and v != b and v != u:
s += sizes[v]
if s > best:
best = s
return best