Minimum Water Cells to Connect Two Land Masses
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests ability to combine flood-fill island identification with multi-source BFS to find the shortest water path bridging two disconnected land regions in a grid.
Problem
You have an R × C grid of 0s and 1s. Each 1 is land; each 0 is water. The grid contains exactly two land masses, where each land mass is a group of 1-cells connected through up, down, left, and right neighbors.
Your goal is to build the shortest possible bridge between the two land masses by converting water cells to land. Return the minimum number of water cells that must be converted so that a 4-directional path of 1s runs continuously from one land mass to the other.
Input
grid: a 2-D list of integers, each either0(water) or1(land)
Output
- An integer: the fewest water cells that need to be flipped to
1to connect the two land masses
How to think about it
The problem reduces to a shortest-path question on an unweighted grid. The cost of a path through water equals the number of water cells it passes through, and you want to minimize that count.
A useful two-phase strategy:
- Identify one land mass completely. Use a flood fill (BFS or iterative DFS) starting from any land cell you find. Collect every cell that belongs to that land mass.
- Expand outward with multi-source BFS. Treat every cell of the first land mass as a starting point at distance 0. Spread outward through water, layer by layer. The moment you reach any cell belonging to the second land mass, the number of complete water layers you have crossed is the answer.
Constraints
1 <= R, C <= 200- Every cell is either
0or1 - The grid contains exactly two 4-directionally connected land masses
- The two land masses are never already touching, so the answer is always at least
1 - Avoid standard recursive DFS for the flood fill — deep grids can exceed Python's default recursion limit; use an explicit stack or BFS instead
Examples
Example 1
Input: min_bridge_flips([[0, 1, 0], [0, 0, 0], [0, 0, 1]])
Output: 2
Example 2
Input: min_bridge_flips([[1, 0, 0, 0, 1]])
Output: 3
Example 3
Input: min_bridge_flips([[1, 0], [0, 1]])
Output: 1
Hints
Hint 1
Scan the grid row by row until you find the first land cell, then use an iterative flood fill (explicit stack or BFS) to collect every cell of that island into a set — that entire set becomes your starting frontier.
Hint 2
Feed all cells of the first island into a BFS queue at distance 0, then expand level by level through water cells. Process each level completely before incrementing your step counter so that the counter tracks full water layers crossed, not individual cell visits.
Hint 3
The first time BFS reaches a cell that is land but was never part of the first island, you have touched the second island — return the current step count immediately. You do not need to finish processing that layer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
High-level idea
The problem is a shortest unweighted-path query on a grid. Converting a water cell to land to "build" the bridge is equivalent to paying a cost of 1 per water cell crossed. We want to minimize that cost, which is just the count of water cells on the shortest path from any cell of land mass A to any cell of land mass B.
Two standard techniques combine cleanly here.
Phase 1 — label both islands with flood fill
Scan the grid in row-major order. Each time a land cell is found that has not yet been assigned to an island, launch an iterative BFS (using an explicit list as a growing queue) from that cell. Every land cell reachable from it gets the same island_id written into a separate component array. Because the problem guarantees exactly two islands, this loop runs exactly twice.
Using an explicit list/queue for the flood fill instead of recursion avoids Python hitting its default recursion limit on a large, dense island (up to 40 000 cells on a 200 × 200 grid).
Phase 2 — multi-source BFS from island 1
Seed a BFS queue with every cell of island 1, each at distance 0. A distance array (initialised to −1) tracks how many water cells have been crossed to reach each position.
Expand outward:
- Skip cells already visited (
distance != -1). - When a neighbor is a water cell, record its distance as
distance[current] + 1and enqueue it. - When a neighbor is a land cell belonging to island 2, return
distance[current]immediately. That value is the number of water cells on the shortest path, i.e., the minimum number of flips.
Why this is correct
Multi-source BFS is equivalent to adding a virtual zero-cost super-source connected to every cell of island 1, then running standard BFS. BFS on an unweighted graph produces exact shortest distances in non-decreasing order, so the first time any cell of island 2 is reached, no shorter bridge can exist.
The returned value distance[r][c] counts only the water cells traversed to arrive at position (r, c) — it does not count the landing cell on island 2 (already land, no flip needed) or the source cells on island 1 (also already land). This is exactly the number of flips required.
Because the two islands are guaranteed never to be adjacent, the answer is always at least 1.
Complexity
- Time: O(R · C). Every cell is enqueued at most once in the flood fill and at most once in the BFS. Each visit inspects 4 neighbors.
- Space: O(R · C) for the
componentarray, thedistancearray, and the BFS queue.
For the maximum grid size of 200 × 200 = 40 000 cells this is very fast in practice.
Reference solution
from collections import deque
from typing import List
def min_bridge_flips(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
# component[r][c] stores which island (1 or 2) a land cell belongs to;
# 0 means water or not yet visited.
component = [[0] * cols for _ in range(rows)]
islands = []
# Phase 1: flood-fill to label both islands.
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1 and component[r][c] == 0:
island_id = len(islands) + 1
cells = [(r, c)]
component[r][c] = island_id
for cr, cc in cells:
for nr, nc in ((cr - 1, cc), (cr + 1, cc),
(cr, cc - 1), (cr, cc + 1)):
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] == 1
and component[nr][nc] == 0):
component[nr][nc] = island_id
cells.append((nr, cc))
islands.append(cells)
# Phase 2: multi-source BFS from every cell of island 1 through water.
# distance[r][c] = number of water cells flipped to reach (r, c) from island 1.
queue = deque()
distance = [[-1] * cols for _ in range(rows)]
for r, c in islands[0]:
queue.append((r, c))
distance[r][c] = 0
while queue:
r, c = queue.popleft()
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols:
if component[nr][nc] == 2:
# Reached island 2; distance[r][c] water cells were crossed.
return distance[r][c]
if distance[nr][nc] == -1 and grid[nr][nc] == 0:
distance[nr][nc] = distance[r][c] + 1
queue.append((nr, nc))
return -1 # Unreachable given the problem's guarantee of exactly two islands.