{x}
blog image

Shortest Bridge

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 Explanation:

This problem asks to find the minimum number of 0s (water cells) to flip in order to connect two islands in a binary matrix. The solution uses a Breadth-First Search (BFS) algorithm after first identifying one of the islands.

Algorithm:

  1. Island Identification and DFS: The solution starts by finding the coordinates of a cell belonging to one of the islands (grid[i][j] == 1). A Depth-First Search (DFS) is then used to mark all cells belonging to this island with a value of 2. This is crucial to distinguish this island from the other during the subsequent BFS. The DFS also adds all cells of the first island to a queue q.

  2. Breadth-First Search (BFS): A BFS is initiated from the cells identified in the first step. The BFS expands outwards, layer by layer, exploring the neighbouring cells.

    • If a neighbour is part of the second island (grid[x][y] == 1), the search is complete, and the minimum number of steps taken (ans) is the result.
    • If a neighbour is a water cell (grid[x][y] == 0), it is marked as visited (grid[x][y] = 2) and added to the queue for exploration in the next layer.
  3. Distance Calculation: The ans variable keeps track of the number of layers (distance) in the BFS. This distance represents the minimum number of 0s that need to be flipped to connect the two islands.

Time Complexity: O(N^2), where N is the size of the grid. Both DFS and BFS visit each cell at most once.

Space Complexity: O(N^2) in the worst case, to store the queue q which could potentially hold all cells of the grid if the islands are very far apart.

Code Explanation (Python):

class Solution:
    def shortestBridge(self, grid: List[List[int]]) -> int:
        def dfs(i, j):
            q.append((i, j))
            grid[i][j] = 2
            for a, b in pairwise(dirs): #iterates through neighbours
                x, y = i + a, j + b
                if 0 <= x < n and 0 <= y < n and grid[x][y] == 1:
                    dfs(x, y)
 
        n = len(grid)
        dirs = (-1, 0, 1, 0, -1) #directions to check neighbours
        q = deque() #queue for BFS
        #find the first island cell
        i, j = next((i, j) for i in range(n) for j in range(n) if grid[i][j])
        dfs(i, j) #Mark the first island and add to queue
        ans = 0
        while 1: #BFS
            for _ in range(len(q)): #Process all nodes at current level
                i, j = q.popleft()
                for a, b in pairwise(dirs):
                    x, y = i + a, j + b
                    if 0 <= x < n and 0 <= y < n:
                        if grid[x][y] == 1:
                            return ans #Found the second island
                        if grid[x][y] == 0:
                            grid[x][y] = 2 #Mark as visited
                            q.append((x, y)) #Add to queue
            ans += 1 #increment distance

The other languages (Java, C++, Go) follow a very similar structure and logic, adapting the syntax and data structures to their respective languages. The core algorithm remains the same. The pairwise function in Python helps in iterating through neighbor cells efficiently. Similar functionality is achieved through arrays in other languages.