Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island).

Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island).
from collections import deque
def bridge(g):
    n = len(g); q = deque(); seen = set()
    def dfs(r, c):
        if not (0 <= r < n and 0 <= c < n) or g[r][c] != 1 or (r, c) in seen: return
        seen.add((r, c)); q.append((r, c, 0))
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)): dfs(x, y)
    dfs(*next((r, c) for r in range(n) for c in range(n) if g[r][c]))
    while q:
        r, c, d = q.popleft()
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < n and 0 <= y < n and (x, y) not in seen:
                if g[x][y] == 1: return d
                seen.add((x, y)); q.append((x, y, d + 1))
print(bridge([[1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]))
What is printed?
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: A. 4

The first island is {(0,0), (0,1), (1,0)}; the second is {(2,4), (3,3), (3,4), (4,4)}. The closest pair of cells across the islands, e.g. (0,1)–(2,4) or (1,0)–(3,3), is at Manhattan distance 5, so 4 water cells lie between them. Multi-source BFS from the whole first island finds this in O(n²): 4 flips.

More Coding Interview Problems questions

Exams that ask this topic