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].length2 <= n <= 100grid[i][j] is either 0 or 1.grid.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:
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:
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_lengthTo 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:
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| Case | How to Handle |
|---|---|
| Minimum possible grid size where n equals 2 and both islands are adjacent | The Breadth-First Search immediately finds a distance of zero flips and terminates correctly. |
| Islands separated by a single row or column of water | 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 | 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 | 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 | 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 | 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 | Implementing iterative DFS or relying on a properly sized queue prevents stack overflow errors on large components. |