Shortest Bridge

Medium

Topics
ArrayDFSBFSMatrix

You are given an n x n binary grid containing exactly two islands. An island is a group of 1s connected 4-directionally.

You may change 0s to 1s to connect the two islands into one. Return the smallest number of 0s you must change.

Example 1

00111001
first islandsecond islandwater flipped to land
The grid holds exactly two islands of 1s, shaded separately, and the answer is the fewest water cells that have to be flipped to 1 before the two become one connected island. Here 1 cell is enough, and the third shade marks one choice of which — other choices of the same size usually exist, and only the count is returned. Cells touch only up, down, left and right, so a diagonal gap still has to be bridged.
Both islands already exist; nothing is being created from scratch.
Input:  grid = [[0,1],[1,0]]
Output: 1
Explanation: The two cells are diagonal neighbours, which does not connect them; filling either empty cell does.

Example 2

001010002001012
first islandsecond islandwater flipped to land
Input:  grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Explanation: The islands are at opposite corners; two filled cells bridge them.

Example 3

01111111000121010131000141111101234
first islandsecond islandwater flipped to land
Input:  grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
Explanation: A ring around a single cell — one fill reaches it.

Constraints

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is 0 or 1
  • There are exactly two islands
Editorial — intuition, approach, complexity and pitfalls

Intuition

The distance wanted is between two regions, not two cells, so the first job is to tell the islands apart — the input does not label them.

Once one island is identified as a whole, the question becomes: how far is the nearest cell of the other island from any cell of this one? That is a distance from a set rather than from a point, which is why starting the measurement from every cell of the first island at once is the natural move: the frontier then expands outward from the island’s whole coastline simultaneously, and the first time it touches the second island it has found the minimum.

The count to return is the number of water cells filled, which is one less than the number of expansion steps taken — the step that lands on the second island’s own cell fills nothing.

Note the connectivity rule cuts both ways: diagonal neighbours do not join islands, which is why example 1 answers 1 rather than 0.

Approach

  1. Scan for the first 1 and collect its entire island, marking those cells so they are not mistaken for the other island later.
  2. Seed a frontier with every cell of that island at distance 0.
  3. Expand the frontier one ring at a time over the 4 directions. A cell already seen is skipped.
  4. When the frontier reaches a 1 that is not part of the first island, the answer is the number of rings expanded minus one.

Walkthrough

grid = [[0,1,0],
        [0,0,0],
        [0,0,1]]

first island found: the single cell (0,1)
frontier starts as {(0,1)} at distance 0

ring 1   (0,0) (0,2) (1,1)              all water
ring 2   (1,0) (1,2) (2,1)              all water
ring 3   (2,0) (2,2)                    (2,2) is the other island

reached at ring 3, so the cells filled are rings 1 and 2
answer 2

The frontier grew from the island’s whole edge at once, so the
first contact is the closest contact -- there is nothing to
compare afterwards.

Complexity

  • Time — O(n^2): each cell is collected once and expanded once.
  • Space — O(n^2): the seen matrix and the frontier.

Common Pitfalls

  • Expanding from a single cell of the first island rather than from all of it. The nearest point of the second island may be opposite a different part of the coastline, and a single-source measurement finds a longer bridge.
  • Not marking the first island before expanding, so the frontier immediately "reaches" its own cells and answers 0.
  • Returning the ring count rather than the ring count minus one. The last step lands on land and fills nothing.
  • Treating diagonal neighbours as connected when identifying islands. Example 1 has two islands precisely because they are not.

Full Solution — all languages

class Solution:
    def shortestBridge(self, grid):
        from collections import deque
        n = len(grid)
        DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))
        seen = [[False] * n for _ in range(n)]

        start = None
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 1:
                    start = (r, c)
                    break
            if start:
                break

        stack = [start]
        seen[start[0]][start[1]] = True
        island = set()
        frontier = deque()
        while stack:
            r, c = stack.pop()
            island.add((r, c))
            frontier.append((r, c))
            for dr, dc in DIRS:
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1 and not seen[nr][nc]:
                    seen[nr][nc] = True
                    stack.append((nr, nc))

        steps = 0
        while frontier:
            for _ in range(len(frontier)):
                r, c = frontier.popleft()
                for dr, dc in DIRS:
                    nr, nc = r + dr, c + dc
                    if not (0 <= nr < n and 0 <= nc < n) or seen[nr][nc]:
                        continue
                    if grid[nr][nc] == 1 and (nr, nc) not in island:
                        return steps
                    seen[nr][nc] = True
                    frontier.append((nr, nc))
            steps += 1
        return -1
SensAI
Beta
Tap the mic to stop voice mode