KatInterview

971. Shortest Bridge

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of water cells (0) we need to flip to land (1) to connect two separate islands. This is equivalent to finding the shortest path of water cells between the two islands. The length of this path is the number of water cells, which corresponds to the number of flips needed.

Solution

Shortest Bridge in Python

import collections

class Solution:
    def shortestBridge(self, grid: list[list[int]]) -> int:
        n = len(grid)
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        
        # This queue will store the cells of the first island for the multi-source BFS.
        first_island_q = collections.deque()
        
        # Step 1: Find the first island using BFS (to avoid recursion depth issues) 
        # and add its cells to first_island_q.
        found = False
        for r in range(n):
            if found:
                break
            for c in range(n):
                if grid[r][c] == 1:
                    # Start BFS from this cell to find all parts of the first island.
                    q_bfs = collections.deque([(r, c)])
                    grid[r][c] = 2  # Mark as visited part of the first island.
                    first_island_q.append((r, c))
                    
                    while q_bfs:
                        row, col = q_bfs.popleft()
                        for dr, dc in directions:
                            nr, nc = row + dr, col + dc
                            if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
                                grid[nr][nc] = 2  # Mark as visited.
                                first_island_q.append((nr, nc))
                                q_bfs.append((nr, nc))
                    
                    found = True
                    break
        
        # Step 2: Multi-source BFS to find the shortest path to the second island.
        distance = 0
        while first_island_q:
            level_size = len(first_island_q)
            for _ in range(level_size):
                r, c = first_island_q.popleft()
                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < n and 0 <= nc < n:
                        if grid[nr][nc] == 1:  # Found the second island.
                            return distance
                        if grid[nr][nc] == 0:  # This is a water cell we can flip.
                            grid[nr][nc] = 2  # Mark water cell as visited to avoid cycles.
                            first_island_q.append((nr, nc))
            distance += 1
            
        return -1  # Should not be reached given problem constraints.

Shortest Bridge in Java

class Solution {
    private int n;
    private Queue<int[]> q = new LinkedList<>();

    public int shortestBridge(int[][] grid) {
        this.n = grid.length;
        boolean found = false;
        // Step 1: Find the first island using DFS, mark it with 2, and collect its cells in a queue.
        for (int i = 0; i < n; i++) {
            if (found) break;
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    dfs(grid, i, j);
                    found = true;
                    break;
                }
            }
        }

        // Step 2: Multi-source BFS to find the shortest path to the second island.
        int distance = 0;
        int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int[] cell = q.poll();
                for (int[] dir : dirs) {
                    int r = cell[0] + dir[0];
                    int c = cell[1] + dir[1];
                    if (r >= 0 && r < n && c >= 0 && c < n) {
                        if (grid[r][c] == 1) {
                            // Found the second island, return the current distance
                            return distance;
                        }
                        if (grid[r][c] == 0) {
                            // This is a water cell, mark it as visited and add to queue
                            grid[r][c] = 2;
                            q.add(new int[]{r, c});
                        }
                    }
                }
            }
            distance++;
        }
        return -1; // Should not be reached based on problem constraints
    }

    private void dfs(int[][] grid, int r, int c) {
        // Check for boundaries or if the cell is not part of the island we're looking for
        if (r < 0 || r >= n || c < 0 || c >= n || grid[r][c] != 1) {
            return;
        }
        // Mark the cell as part of the first island (value 2)
        grid[r][c] = 2;
        // Add the cell to the queue for the BFS phase
        q.add(new int[]{r, c});
        // Recursively explore neighbors
        dfs(grid, r + 1, c);
        dfs(grid, r - 1, c);
        dfs(grid, r, c + 1);
        dfs(grid, r, c - 1);
    }
}

Shortest Bridge in C++

class Solution {
public:
    int shortestBridge(vector<vector<int>>& grid) {
        int n = grid.size();
        queue<pair<int, int>> q;
        bool found_island = false;

        // Step 1: Find the first island using DFS, mark it with 2, and add its cells to a queue.
        for (int i = 0; i < n; ++i) {
            if (found_island) break;
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    dfs(grid, i, j, n, q);
                    found_island = true;
                    break;
                }
            }
        }

        // Step 2: Perform a multi-source BFS starting from all cells of the first island.
        int distance = 0;
        vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (!q.empty()) {
            int level_size = q.size();
            for (int i = 0; i < level_size; ++i) {
                auto [r, c] = q.front();
                q.pop();

                for (auto& dir : dirs) {
                    int nr = r + dir.first;
                    int nc = c + dir.second;

                    if (nr >= 0 && nr < n && nc >= 0 && nc < n) {
                        if (grid[nr][nc] == 1) {
                            // Found the second island.
                            return distance;
                        }
                        if (grid[nr][nc] == 0) {
                            // Expand to this water cell.
                            grid[nr][nc] = 2; // Mark as visited to avoid cycles.
                            q.push({nr, nc});
                        }
                    }
                }
            }
            distance++;
        }
        return -1; // Should not be reached.
    }

private:
    void dfs(vector<vector<int>>& grid, int r, int c, int n, queue<pair<int, int>>& q) {
        // Boundary and visited checks
        if (r < 0 || r >= n || c < 0 || c >= n || grid[r][c] != 1) {
            return;
        }
        // Mark as part of island 1 and add to the queue for BFS
        grid[r][c] = 2;
        q.push({r, c});

        // Recursively call for all 4 directions
        dfs(grid, r + 1, c, n, q);
        dfs(grid, r - 1, c, n, q);
        dfs(grid, r, c + 1, n, q);
        dfs(grid, r, c - 1, n, q);
    }
};

Shortest Bridge in TypeScript

function shortestBridge(grid: number[][]): number {
    const n = grid.length;
    const islandQueue: [number, number][] = [];
    const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];

    // Step 1: Find the first island using BFS and populate islandQueue.
    // Using BFS here to avoid potential stack overflow on large, thin islands.
    let found = false;
    for (let i = 0; i < n; i++) {
        if (found) break;
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === 1) {
                const q: [number, number][] = [[i, j]];
                grid[i][j] = 2; // Mark as part of island 1
                islandQueue.push([i, j]);
                
                let head = 0;
                while(head < q.length) {
                    const [r, c] = q[head++]; // Use index for efficient queue
                    for (const [dr, dc] of directions) {
                        const nr = r + dr;
                        const nc = c + dc;
                        if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] === 1) {
                            grid[nr][nc] = 2;
                            islandQueue.push([nr, nc]);
                            q.push([nr, nc]);
                        }
                    }
                }
                found = true;
                break;
            }
        }
    }

    // Step 2: Multi-source BFS to find the shortest bridge.
    let distance = 0;
    let head = 0;
    while (head < islandQueue.length) {
        const levelSize = islandQueue.length - head;
        for (let i = 0; i < levelSize; i++) {
            const [r, c] = islandQueue[head++];
            for (const [dr, dc] of directions) {
                const nr = r + dr;
                const nc = c + dc;
                if (nr >= 0 && nr < n && nc >= 0 && nc < n) {
                    if (grid[nr][nc] === 1) {
                        // Found the second island.
                        return distance;
                    }
                    if (grid[nr][nc] === 0) {
                        // Water cell, mark as visited and enqueue.
                        grid[nr][nc] = 2;
                        islandQueue.push([nr, nc]);
                    }
                }
            }
        }
        distance++;
    }

    return -1; // Should not be reached.
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.