Algo-Sim › Grid Graphs

Shortest Bridge

Medium · Grid Graphs · step through it in Java, Python and C++ on your own input

Flood-fill one island into a queue, then BFS outward through the water; the ring that first touches the other island is the answer.

Problem

An n × n grid of 0 (water) and 1 (land) holds exactly two islands, each a group of 4-directionally connected 1s. Return the fewest 0s you must flip to 1 to join the two islands into one.

Constraints

Edge cases to test

Follow-up questions

Why flood-fill first?
All cells of the first island are sources at distance 0, so one BFS finds the nearest cell of the second island: O(n²).
Why not BFS from each cell?
Each search would be O(n²), so trying every cell costs O(n⁴).

Solution

Java

public int shortestBridge(int[][] grid) {
    int n = grid.length;
    Queue<int[]> queue = new ArrayDeque<>();
    find:
    for (int r = 0; r < n; r++) {
        for (int c = 0; c < n; c++) {
            if (grid[r][c] == 1) { mark(grid, r, c, queue); break find; }
        }
    }
    int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
    for (int flips = 0; ; flips++) {
        for (int size = queue.size(); size > 0; size--) {
            int[] cell = queue.poll();
            for (int[] d : dirs) {
                int nr = cell[0] + d[0], nc = cell[1] + d[1];
                if (nr < 0 || nc < 0 || nr >= n || nc >= n || grid[nr][nc] == 2) continue;
                if (grid[nr][nc] == 1) return flips;
                grid[nr][nc] = 2;
                queue.offer(new int[] { nr, nc });
            }
        }
    }
}

// Paint the first island 2 and queue all of its cells.
private void mark(int[][] grid, int r, int c, Queue<int[]> queue) {
    int n = grid.length;
    if (r < 0 || c < 0 || r >= n || c >= n || grid[r][c] != 1) return;
    grid[r][c] = 2;
    queue.offer(new int[] { r, c });
    mark(grid, r + 1, c, queue);
    mark(grid, r - 1, c, queue);
    mark(grid, r, c + 1, queue);
    mark(grid, r, c - 1, queue);
}

Python

from collections import deque

def shortest_bridge(grid):
    n = len(grid)
    queue = deque()
    start = next((r, c) for r in range(n) for c in range(n) if grid[r][c] == 1)
    mark(grid, *start, queue)
    flips = 0
    while True:
        for _ in range(len(queue)):
            cr, cc = queue.popleft()
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = cr + dr, cc + dc
                if not (0 <= nr < n and 0 <= nc < n) or grid[nr][nc] == 2:
                    continue
                if grid[nr][nc] == 1:
                    return flips
                grid[nr][nc] = 2
                queue.append((nr, nc))
        flips += 1


# Paint the first island 2 and queue all of its cells.
def mark(grid, r, c, queue):
    n = len(grid)
    if not (0 <= r < n and 0 <= c < n) or grid[r][c] != 1:
        return
    grid[r][c] = 2
    queue.append((r, c))
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        mark(grid, r + dr, c + dc, queue)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int shortestBridge(vector<vector<int>> &grid) {
        int n = int(grid.size());
        deque<pair<int, int>> queue;
        bool found = false;
        for (int r = 0; r < n && !found; r++) {
            for (int c = 0; c < n && !found; c++) {
                if (grid[r][c] == 1) {
                    mark(grid, r, c, queue);
                    found = true;
                }
            }
        }
        vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for (int flips = 0;; flips++) {
            for (int size = int(queue.size()); size > 0; size--) {
                auto [r, c] = queue.front();
                queue.pop_front();
                for (vector<int> &d : dirs) {
                    int nr = r + d[0], nc = c + d[1];
                    if (nr < 0 || nc < 0 || nr >= n || nc >= n || grid[nr][nc] == 2)
                        continue;
                    if (grid[nr][nc] == 1)
                        return flips;
                    grid[nr][nc] = 2;
                    queue.push_back({nr, nc});
                }
            }
        }
    }

  private:
    // Paint the first island 2 and queue all of its cells.
    void mark(vector<vector<int>> &grid, int r, int c, deque<pair<int, int>> &queue) {
        int n = int(grid.size());
        if (r < 0 || c < 0 || r >= n || c >= n || grid[r][c] != 1)
            return;
        grid[r][c] = 2;
        queue.push_back({r, c});
        mark(grid, r + 1, c, queue);
        mark(grid, r - 1, c, queue);
        mark(grid, r, c + 1, queue);
        mark(grid, r, c - 1, queue);
    }
};

More Grid Graphs problems