Taro Logo

Shortest Bridge

#2 Most AskedMedium
0 views
Topics:
ArraysGraphs

You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.

You may change 0's to 1's to connect the two islands to form one island.

Return the smallest number of 0's you must flip to connect the two islands.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is either 0 or 1.
  • There are exactly two islands in grid.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the dimensions ($n \times n$) of the grid, and what is the maximum size we should expect for $n$?
  2. How are the islands defined in terms of connectivity—are they connected 4-directionally (up, down, left, right) or 8-directionally including diagonals?
  3. Is the grid guaranteed to be at least $2 \times 2$ in size, and will there always be exactly two distinct islands present?
  4. Can the grid be modified in place during the traversal, or should we avoid mutating the input matrix?
  5. What should be returned if no bridge can be formed, or is a solution guaranteed to always exist per the problem description?

Brute Force Solution

Approach

Imagine you have two separate islands in a large grid of water and you want to build the shortest possible bridge of land between them. The brute force strategy involves testing every single piece of water to see how far it is from the first island, testing every piece of water to see how far it is from the second island, and then finding the combination that connects the two islands with the fewest steps.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the entire grid and identifying all the land belonging to the first island and all the land belonging to the second island.
  2. Pick a piece of water adjacent to the first island.
  3. Imagine drawing a path from that water piece to every single piece of water connected to the second island, checking all possible paths of various lengths.
  4. Repeat this checking process for every single piece of water touching the first island.
  5. Compare the lengths of all the paths you tested that bridge the gap between the two islands.
  6. Select the shortest path among all the possibilities you explored, which represents your shortest bridge.

Code Implementation

class Solution:
    def shortestBridge(self, grid: list[list[int]]) -> int:
        row_count = len(grid)
        col_count = len(grid[0])
        first_island_cells = []
        second_island_cells = []
        visited_cells = set()

        def explore_island(current_row, current_col, island_container):
            if (current_row < 0 or current_row >= row_count or 
                current_col < 0 or current_col >= col_count or 
                grid[current_row][current_col] == 0 or 
                (current_row, current_col) in visited_cells):
                return
            visited_cells.add((current_row, current_col))
            island_container.append((current_row, current_col))
            explore_island(current_row + 1, current_col, island_container)
            explore_island(current_row - 1, current_col, island_container)
            explore_island(current_row, current_col + 1, island_container)
            explore_island(current_row, current_col - 1, island_container)

        # We partition the grid by finding all connected components to separate the two distinct islands
        for row_index in range(row_count):
            for col_index in range(col_count):
                if grid[row_index][col_index] == 1 and not first_island_cells and (row_index, col_index) not in visited_cells:
                    explore_island(row_index, col_index, first_island_cells)
                elif grid[row_index][col_index] == 1 and first_island_cells and (row_index, col_index) not in visited_cells:
                    explore_island(row_index, col_index, second_island_cells)

        shortest_bridge_length = float('inf')

        # We iterate over every land cell on the first island to evaluate all potential bridging paths
        for cell_from_first in first_island_cells:
            for cell_from_second in second_island_cells:
                
                current_distance = abs(cell_from_first[0] - cell_from_second[0]) + abs(cell_from_first[1] - cell_from_second[1]) - 1
                if current_distance < shortest_bridge_length:
                    shortest_bridge_length = current_distance

        return shortest_bridge_length

Big(O) Analysis

Time Complexity
O(N^2) – Let N be the total number of cells in the N x N grid. Identifying the two islands requires scanning the entire grid once, which takes O(N) operations. Then, the brute-force strategy evaluates every water cell and checks its distance to both islands, potentially traversing paths that cover a fraction of the total grid for multiple starting points. Summing these potential path-checking operations across the grid results in roughly N^2 * (N^2)/2 total steps in the worst-case scenario. Simplifying this expression by dropping constants and lower-order terms yields a final time complexity of O(N^2).
Space Complexity
O(N) – To analyze the space complexity, let N be the total number of cells in the grid. The algorithm uses a queue for breadth-first search and a visited set or matrix to keep track of explored land and water locations. In the worst-case scenario, such as a spiral or large connected components, the queue and visited structures can store up to N cells simultaneously. Therefore, the auxiliary space grows linearly with the grid size, simplifying to Big O of N.

Optimal Solution

Approach

To find the shortest path connecting two separate islands, we can think of the first island as a spreading wave that slowly expands outward step by step. Once this expanding wave reaches the second island, the total number of steps it took represents the shortest possible bridge.

Here's how the algorithm would work step-by-step:

  1. Scan the entire map until you find the very first piece of land belonging to the initial island.
  2. Explore every connected piece of land attached to that first piece so you know the exact boundaries and shape of the entire first island.
  3. Mark every single part of this first island as a visited frontier, preparing to expand outward.
  4. Begin a wave-like expansion from the edges of the first island, moving step by step into the surrounding water in all directions at the same time.
  5. Keep track of how many steps or rings the wave has traveled as it expands further into the water.
  6. Check if the expanding wave touches any piece of land belonging to the second island.
  7. Stop expanding the moment the wave reaches the second island and report the exact number of steps the wave took to bridge the gap.

Code Implementation

class Solution:
    def shortestBridge(self, grid: list[list[int]]) -> int:
        grid_row_count = len(grid)
        grid_col_count = len(grid[0])
        queue_for_bfs = []
        visited_set = set()
        
        def depth_first_search(row_index, col_index):
            if (row_index < 0 or row_index >= grid_row_count or 
                col_index < 0 or col_index >= grid_col_count or 
                grid[row_index][col_index] == 0 or 
                (row_index, col_index) in visited_set):
                return
            visited_set.add((row_index, col_index))
            queue_for_bfs.append((row_index, col_index))
            depth_first_search(row_index + 1, col_index)
            depth_first_search(row_index - 1, col_index)
            depth_first_search(row_index, col_index + 1)
            depth_first_search(row_index, col_index - 1)

        # Locate the first island so we can isolate its complete boundary.
        found_first_island = False
        for row_index in range(grid_row_count):
            if found_first_island:
                break
            for col_index in range(grid_col_count):
                if grid[row_index][col_index] == 1:
                    depth_first_search(row_index, col_index)
                    found_first_island = True
                    break

        bridge_distance = 0
        direction_offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]

        # Expand outward level by level to find the minimum distance to the second island.
        while queue_for_bfs:
            next_level_queue = []
            for current_row, current_col in queue_for_bfs:
                for row_offset, col_offset in direction_offsets:
                    neighbor_row = current_row + row_offset
                    neighbor_col = current_col + col_offset
                    
                    if 0 <= neighbor_row < grid_row_count and 0 <= neighbor_col < grid_col_count and (neighbor_row, neighbor_col) not in visited_set:
                        if grid[neighbor_row][neighbor_col] == 1:
                            return bridge_distance
                        visited_set.add((neighbor_row, neighbor_col))
                        next_level_queue.append((neighbor_row, neighbor_col))
            
            queue_for_bfs = next_level_queue
            bridge_distance += 1

        return bridge_distance

Big(O) Analysis

Time Complexity
O(n^2) – Scanning the grid to find the first island requires visiting each of the n cells in the n by n matrix. The Depth First Search expansion to map the entire first island and mark its boundaries visits every cell of that island at most once. The Breadth First Search wave expansion visits each water and land cell in the grid at most once as it spreads outward. Combining these phases means every cell in the n by n grid is processed a constant number of times, resulting in roughly n squared operations which simplifies to O(n^2).
Space Complexity
O(N) – To analyze the space complexity, let N be the total number of cells in the grid, which has dimensions N by N or N total elements. The algorithm uses a queue data structure to track the visited frontier and coordinate the wave-like expansion across the water. In the worst-case scenario, such as a spiral or a large boundary, the queue and the visited set will store a linear number of cells proportional to N. Therefore, the auxiliary space complexity simplifies to Big O of N due to these explicitly maintained tracking structures.

Edge Cases

Minimum possible grid size where n equals 2 and both islands are adjacent
How to Handle:
The Breadth-First Search immediately finds a distance of zero flips and terminates correctly.
Islands separated by a single row or column of water
How to Handle:
The algorithm expands the first island by one level and touches the second island yielding a bridge length of one.
Maximum grid dimensions up to one hundred by one hundred
How to Handle:
Using a visited matrix and queue-based BFS ensures time and space complexity remain optimal without exceeding execution limits.
Deeply nested or irregularly shaped islands with convoluted borders
How to Handle:
Multi-source BFS from all cells of the first island ensures we find the absolute shortest path regardless of shape.
Grid containing only land cells without water or only water without land
How to Handle:
Problem constraints guarantee exactly two separate islands exist so this scenario is invalid by definition.
Queue memory usage scaling heavily on large grids with massive water expanses
How to Handle:
Updating visited status upon initial discovery prevents redundant node processing and keeps memory consumption bounded.
Recursion depth limit exceeded during deep Depth-First Search island discovery
How to Handle:
Implementing iterative DFS or relying on a properly sized queue prevents stack overflow errors on large components.
0/3 completed