Minimum Flips to Join Two Islands

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given an R x C grid of integers containing only 0 (water) and 1 (land), two land squares belong to the same island whenever a path of orthogonally adjacent land squares (up, down, left, or right; never diagonal) joins them. The input map always contains exactly two distinct islands.

In one operation, you can turn any single water square (0) into land (1). Compute and return the smallest number of water squares that must be converted so both islands merge into one orthogonally connected landmass.

Examples

Example 1

Input:
grid = [
  [1, 1, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 1]
]

Output: 3

Explanation: One island occupies (0, 0) and (0, 1), while the second sits at (2, 3). Converting the three water squares (0, 2), (1, 2), and (2, 2) (among several equal-length routes) joins (0, 1) to (2, 3), and no two-square conversion can reach across both the two-row and two-column gap.

Example 2

Input:
grid = [
  [0, 1, 1],
  [1, 0, 0],
  [1, 0, 0]
]

Output: 1

Explanation: Because diagonal neighbors do not touch, [(0, 1), (0, 2)] and [(1, 0), (2, 0)] are separate islands even though (0, 1) and (1, 0) meet at a corner. Converting (0, 0) (or (1, 1)) links both islands with just 1 operation.

Example 3

Input:
grid = [
  [1],
  [0],
  [0],
  [0],
  [0],
  [1]
]

Output: 4

Explanation: In this single-column map, four water squares sit between (0, 0) and (5, 0). Every intermediate cell must become 1, requiring 4 conversions.

Constraints

  • 1 <= R, C <= 200, where R = len(grid) and C = len(grid[0]).
  • Every entry grid[r][c] is either 0 or 1.
  • grid contains exactly two 4-directionally connected components of 1s.

Step-by-step walkthrough

  1. Restate the problem

    We are given an R × C grid of 0s (water) and 1s (land) containing exactly two islands. Two land cells belong to the same island when you can walk between them using 4-directional steps (up, down, left, right—diagonals do not connect).

    We want the minimum number of 0 cells we must convert to 1 so both islands merge into one connected landmass:

    Input grid:                    Convert three '0' cells (marked *):
      1  1  0  0                     1  1  *  0
      0  0  0  0        --->         0  0  *  0     --> 3 conversions join the islands
      0  0  0  1                     0  0  *  1
    

    Because the two islands start separate, they never share a 4-directional edge, so the answer is always at least 1.

  2. Brute force first: closest pair of land cells

    Suppose we collect every (r, c) cell of Island 1 into list A and every cell of Island 2 into list B. Walking along grid edges between a = (r1, c1) and b = (r2, c2) takes at least |r1 - r2| + |c1 - c2| steps, which passes through |r1 - r2| + |c1 - c2| - 1 intermediate cells.

    Because there are no obstacles and no third island, the closest pair (a, b) always has pure water along any shortest grid walk between them (if a land cell sat in between, it would belong to Island 1 or Island 2 and form an even closer pair!). So the exact answer is:

    minimum over all a in A, b in B  of  (|r1 - r2| + |c1 - c2| - 1)
    

    Why not stop here? On a 200 × 200 grid split down the middle by one column of water, |A| and |B| are each around 20,000 cells. Checking |A| × |B| ≈ 400,000,000 pairs in Python is far too slow.

  3. Key idea: grow Island 1 outward one water ring at a time

    Instead of pairing cells across the two islands, treat all of Island 1 as a single starting region at flip cost 0, and expand outward through water one layer at a time using multi-source breadth-first search (BFS)—a BFS whose queue initially holds every cell of Island 1:

    Start (Island 1 = 0, Island 2 = #):    Layer 1 (cost 1):      Layer 2 (cost 2):      Layer 3 (cost 3):
        0  0  .  .                          0  0  1  .             0  0  1  2             0  0  1  2
        .  .  .  .           --->           1  1  .  .    --->     1  1  2  .    --->     1  1  2  3
        .  .  .  #                          .  .  .  #             2  2  .  #             2  2  3 [#] <-- hit!
    
    • Every cell of Island 1 starts in the queue with flips = 0.
    • All water neighbors touching Island 1 enter the queue with flips = 1.
    • Their unvisited water neighbors enter with flips = 2, and so on.

    Because a FIFO queue processes all cost-k cells before any cost-(k + 1) cell, the very first time a cell at cost k looks at a neighbor that is unvisited land (1), that neighbor belongs to Island 2 and k is guaranteed to be the minimum number of water cells we had to flip.

  4. Phase 1: find and flood-fill Island 1 iteratively

    First we scan the grid to find any one land cell (start_r, start_c)—that cell belongs to Island 1. Then we run a flood fill (visiting every connected land cell of Island 1) so we can mark all of Island 1 with flips = 0 and load all of its cells into our BFS queue.

    Two engineering details matter here:

    1. Use an explicit stack list, not recursion. On a 200 × 200 grid, a winding snake-shaped island can contain 20,000 cells in a single chain, which would crash Python's default recursion limit of 1,000.
    2. Keep flips in a separate R × C table initialized to -1 instead of overwriting grid, so the caller's input list is never mutated.
    from collections import deque
    
    # Four orthogonal step offsets: down, up, right, left.
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    def find_first_land(grid: List[List[int]]) -> Tuple[int, int]:
        """Return (row, col) of the first land cell (value 1) in top-to-bottom reading order."""
        rows = len(grid)
        cols = len(grid[0])
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    return r, c
        raise ValueError("grid contains no land cells")
    
    def shortest_bridge(grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
    
        # flips[r][c] stores:
        #   -1 -> cell has not been visited yet
        #    0 -> cell belongs to Island 1 (zero flips needed to reach it)
        #   k>0 -> water cell reachable from Island 1 by flipping k water cells
        flips = [[-1] * cols for _ in range(rows)]
    
        # Phase 1: flood-fill Island 1 iteratively (avoids recursion-depth crash on large grids)
        # and seed the BFS queue with every cell of Island 1 at cost 0.
        start_r, start_c = find_first_land(grid)
        flips[start_r][start_c] = 0
        # stack: explicit DFS worklist of (row, col) land cells belonging to Island 1.
        stack = [(start_r, start_c)]
        # queue: FIFO deque of (row, col) cells ordered by increasing flip count.
        queue = deque()
    
        while stack:
            r, c = stack.pop()
            queue.append((r, c))
            for dr, dc in DIRECTIONS:
                nr = r + dr
                nc = c + dc
                in_bounds = 0 <= nr < rows and 0 <= nc < cols
                if in_bounds and grid[nr][nc] == 1 and flips[nr][nc] == -1:
                    # Mark upon pushing so the same land cell is never pushed twice.
                    flips[nr][nc] = 0
                    stack.append((nr, nc))
    

    Notice we set flips[nr][nc] = 0 when pushing onto stack, not when popping, so a cell with multiple land neighbors is never added twice.

  5. Phase 2: expand outward through water with BFS

    Now queue holds every cell of Island 1 at flips = 0, and every cell of Island 1 is already marked != -1. We pop from the front of queue and inspect each in-bounds unvisited neighbor (nr, nc):

    • If grid[nr][nc] == 1, it cannot be Island 1 (all of Island 1 already has flips == 0), so we just reached Island 2! Since (nr, nc) is already land, we do not flip it—we return flips[r][c], the count of water cells flipped to reach (r, c).
    • Otherwise grid[nr][nc] == 0 is water: flipping it costs flips[r][c] + 1, so we record that value and push (nr, nc) onto the back of queue.
        # Phase 2: multi-source BFS outward across water, one ring of flipped water per layer.
        while queue:
            r, c = queue.popleft()
            for dr, dc in DIRECTIONS:
                nr = r + dr
                nc = c + dc
                in_bounds = 0 <= nr < rows and 0 <= nc < cols
                if not in_bounds or flips[nr][nc] != -1:
                    continue
    
                if grid[nr][nc] == 1:
                    # All of Island 1 was already marked 0, so an unvisited 1 must be Island 2.
                    # Stepping onto land needs no extra flip, so `flips[r][c]` is the exact answer.
                    return flips[r][c]
    
                # Stepping into unvisited water flips one more water cell.
                flips[nr][nc] = flips[r][c] + 1
                queue.append((nr, nc))
    
        raise ValueError("grid does not contain a second island")
    
  6. Trace Example 1 and Example 2 step by step

    Example 1: grid = [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]

    After Phase 1 (flood-fill Island 1 starting at (0, 0)):
      flips = [[ 0,  0, -1, -1],
               [-1, -1, -1, -1],
               [-1, -1, -1, -1]]
      queue = [(0, 0), (0, 1)]
    
    Layer 1 (pop cost-0 cells) -> water neighbors (1, 0), (1, 1), (0, 2) get cost 1:
      flips = [[ 0,  0,  1, -1],
               [ 1,  1, -1, -1],
               [-1, -1, -1, -1]]
    
    Layer 2 (pop cost-1 cells) -> water neighbors (2, 0), (2, 1), (1, 2), (0, 3) get cost 2:
      flips = [[ 0,  0,  1,  2],
               [ 1,  1,  2, -1],
               [ 2,  2, -1, -1]]
    
    Layer 3 (pop cost-2 cells) -> water neighbors (2, 2) and (1, 3) get cost 3:
      flips = [[ 0,  0,  1,  2],
               [ 1,  1,  2,  3],
               [ 2,  2,  3, -1]]
    
    Pop (2, 2) [cost 3] -> right neighbor (2, 3) has grid[2][3] == 1 and flips == -1!
    Return flips[2][2] = 3.
    

    Example 2: grid = [[0, 1, 1], [1, 0, 0], [1, 0, 0]] (diagonal corner touch)

    • (0, 1) and (1, 0) touch only diagonally, so Phase 1 marks [(0, 1), (0, 2)] with 0.
    • Popping (0, 1) marks water neighbors (1, 1) and (0, 0) with flips = 1.
    • Later, popping (1, 1) (or (0, 0)) sees unvisited land (1, 0) adjacent to it and returns 1.
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    # Four orthogonal step offsets: down, up, right, left.
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    def find_first_land(grid: List[List[int]]) -> Tuple[int, int]:
        """Return (row, col) of the first land cell (value 1) in top-to-bottom reading order."""
        rows = len(grid)
        cols = len(grid[0])
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    return r, c
        raise ValueError("grid contains no land cells")
    
    
    def shortest_bridge(grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
    
        # flips[r][c] stores:
        #   -1 -> cell has not been visited yet
        #    0 -> cell belongs to Island 1 (zero flips needed to reach it)
        #   k>0 -> water cell reachable from Island 1 by flipping k water cells
        flips = [[-1] * cols for _ in range(rows)]
    
        # Phase 1: flood-fill Island 1 iteratively (avoids recursion-depth crash on large grids)
        # and seed the BFS queue with every cell of Island 1 at cost 0.
        start_r, start_c = find_first_land(grid)
        flips[start_r][start_c] = 0
        # stack: explicit DFS worklist of (row, col) land cells belonging to Island 1.
        stack = [(start_r, start_c)]
        # queue: FIFO deque of (row, col) cells ordered by increasing flip count.
        queue = deque()
    
        while stack:
            r, c = stack.pop()
            queue.append((r, c))
            for dr, dc in DIRECTIONS:
                nr = r + dr
                nc = c + dc
                in_bounds = 0 <= nr < rows and 0 <= nc < cols
                if in_bounds and grid[nr][nc] == 1 and flips[nr][nc] == -1:
                    # Mark upon pushing so the same land cell is never pushed twice.
                    flips[nr][nc] = 0
                    stack.append((nr, nc))
    
        # Phase 2: multi-source BFS outward across water, one ring of flipped water per layer.
        while queue:
            r, c = queue.popleft()
            for dr, dc in DIRECTIONS:
                nr = r + dr
                nc = c + dc
                in_bounds = 0 <= nr < rows and 0 <= nc < cols
                if not in_bounds or flips[nr][nc] != -1:
                    continue
    
                if grid[nr][nc] == 1:
                    # All of Island 1 was already marked 0, so an unvisited 1 must be Island 2.
                    # Stepping onto land needs no extra flip, so `flips[r][c]` is the exact answer.
                    return flips[r][c]
    
                # Stepping into unvisited water flips one more water cell.
                flips[nr][nc] = flips[r][c] + 1
                queue.append((nr, nc))
    
        raise ValueError("grid does not contain a second island")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine dropping a custom mold shaped exactly like Island 1 into calm water so ripples spread outward from its entire shoreline at the exact same speed—one grid square per second. At t = 0, every land square of Island 1 is already dry. At t = 1, the ripple covers every water square touching Island 1 (meaning 1 flip reaches them). At t = 2, the ripple covers every water square two steps away (2 flips). The very first moment the expanding ripple touches any land square of Island 2, the number of water rings it crossed is the minimum number of water squares you need to flip.

Why not compare every land square of Island 1 against every land square of Island 2, or run a separate search from each shoreline cell? On a 200 × 200 grid divided by a narrow canal, each island can contain roughly 20,000 land squares, so comparing all pairs takes around 20,000 × 20,000 = 400,000,000 checks. Instead, we first run a flood fill (a graph traversal that visits every connected square of one region) to gather all squares of Island 1, and then run a single multi-source breadth-first search (BFS) (a level-by-level search that starts from many starting squares simultaneously in one shared FIFO queue, where first-in is first-out) so every square on the grid is visited at most once.

Walk through grid = [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]:

  1. Scanning from (0, 0) finds the first 1 at (0, 0). Flood-filling from (0, 0) discovers Island 1 consists of (0, 0) and (0, 1), marks both flips = 0, and seeds both into the queue.
  2. Wave 1 pops the cost-0 cells and marks adjacent water squares (1, 0), (1, 1), and (0, 2) with flips = 1.
  3. Wave 2 pops the cost-1 cells and marks unvisited water squares (2, 0), (2, 1), (1, 2), and (0, 3) with flips = 2.
  4. Wave 3 pops the cost-2 cells and marks (2, 2) and (1, 3) with flips = 3. When (2, 2) (cost 3) is popped next, its right neighbor (2, 3) is an unvisited 1 (Island 2!), so the search immediately returns flips[2][2] = 3.

Complexity

  • Time: O(R × C). Finding the first land square scans at most R × C cells. Both the iterative flood fill and the multi-source BFS mark a cell's flips entry the moment it is pushed, so each of the R × C cells enters stack and queue at most once and checks at most 4 neighbors in O(1) time.
  • Space: O(R × C). The flips table stores one integer per cell (R × C integers), and stack and queue each hold at most R × C cell coordinates at any time.

Edge cases

  • Diagonally touching islands ([[0, 1, 1], [1, 0, 0], [1, 0, 0]]): diagonals are not 4-directionally connected, so they form two distinct islands and converting one shared corner water square (1 flip) joins them.
  • Single-row or single-column grids ([[1], [0], [0], [0], [0], [1]]): neighbor bounds checks (0 <= nr < rows and 0 <= nc < cols) naturally keep the search inside the narrow strip and return 4.
  • One island completely surrounding the other (ring around an inner island): if the outer ring is found first, BFS expands both outward to the border and inward across the lagoon until it touches the inner island.
  • Closest bridge far from the first land cell found: because all cells of Island 1 enter queue at flips = 0, an L-shaped island's far tip starts expanding at the exact same moment as its top-left cell.
  • Long snake-shaped island (~20,000 cells): using an explicit Python list stack instead of recursion avoids RecursionError (1,000-frame default limit).
  • Caller's input grid: storing distances in flips leaves grid completely untouched.

Common mistakes

  • Using recursive DFS for the flood fill: hits Python's recursion limit on a 200 × 200 grid when Island 1 snakes back and forth across thousands of cells.
  • Starting BFS from only (start_r, start_c) instead of the whole first island: steps taken across Island 1's own land cells get counted as if they were water flips, overcounting whenever (start_r, start_c) is not on the closest shoreline.
  • Off-by-one on the return value: returning flips[r][c] + 1 when spotting Island 2 counts the destination land cell itself as a water flip; Island 2 is already land, so flips[r][c] is the exact answer.
  • Marking cells visited upon popping instead of upon pushing: allows the same water cell to be pushed into queue up to four times by different neighbors, bloating memory and runtime.
  • Using list.pop(0) instead of collections.deque.popleft(): list.pop(0) shifts every remaining queue element in O(Q) time, degrading total time toward O((R × C)²).

Alternative approaches

  • All-pairs Manhattan distance (O(|A| × |B|)): Manhattan distance (the grid step distance |r1 - r2| + |c1 - c2| between two coordinates) minus 1 over all pairs (a, b) in Island 1 × Island 2 gives the exact answer because there are no obstacles or third islands, making it a great randomized test oracle on small grids, though too slow when both islands are large.
  • 0-1 BFS (O(R × C)): 0-1 BFS (a shortest-path search on graphs whose edge weights are only 0 or 1, pushing cost-0 steps to the front of a deque and cost-1 steps to the back) can start from (start_r, start_c) alone—walking across Island 1 at cost 0 and water at cost 1 until reaching a land cell at cost > 0—combining both phases into one loop at the expense of slightly trickier logic.

Follow-up questions

  • How can you output the exact grid coordinates of the converted water cells instead of only their count? Store a parent table (parent[nr][nc] = (r, c)) whenever a water cell is first discovered in Phase 2. When (r, c) touches Island 2, follow parent pointers backward from (r, c) until you hit a cell with flips == 0 (Island 1); those intermediate coordinates are the exact water cells to convert, using O(R × C) extra space.
  • How does the algorithm change if islands are connected across all eight directions, including diagonals? Replace DIRECTIONS with all 8 horizontal, vertical, and diagonal offsets in both the flood fill and the BFS. With 8 directions, a single step changes both row and column by 1, so the closest-pair distance changes from Manhattan distance to Chebyshev distance max(|r1 - r2|, |c1 - c2|) - 1.
  • What if every water cell (r, c) has its own positive reclamation cost w[r][c] and you want the cheapest connecting path? Equal BFS layers no longer correspond to equal cost, so replace Phase 2's FIFO queue with Dijkstra's algorithm (a shortest-path search that uses a min-heap priority queue to always expand the lowest-total-cost cell first). Seed the min-heap with (0, r, c) for every cell of Island 1 and add w[nr][nc] when stepping into water, running in O(R · C log(R · C)) time.

Follow-up questions

Similar questions

More Coupang interview questions

All 11 Coupang questions →