Leetcode 934: Shortest Bridge

grid47
grid47
Exploring patterns and algorithms
Aug 5, 2024 8 min read

You are given an n x n binary matrix where 1 represents land and 0 represents water. There are exactly two islands in the grid, and you need to connect them by flipping the smallest number of 0’s to 1’s. An island is a group of 1’s that are connected horizontally or vertically. Your task is to find the minimum number of flips required to connect the two islands.
Problem
Approach
Steps
Complexity
Input: The input consists of an n x n binary matrix, where each cell is either 0 or 1.
Example: Input: grid = [[1,0],[0,1]]
Constraints:
• 2 <= n <= 100
• grid[i][j] is either 0 or 1
• There are exactly two islands in the grid
Output: Return the smallest number of 0's that must be flipped to connect the two islands.
Example: Output: 1
Constraints:
• The grid will always contain exactly two islands.
Goal: To connect the two islands with the minimum number of flips, we first identify one island using depth-first search (DFS), then perform a breadth-first search (BFS) to find the shortest path to the other island by flipping the minimum number of 0's to 1's.
Steps:
• 1. Use DFS to find the first island and store its coordinates.
• 2. Use BFS from the first island to find the shortest path to the second island, counting the number of 0's encountered along the way.
• 3. Return the number of flips required to connect the two islands.
Goal: The grid is square and contains exactly two islands.
Steps:
• 2 <= n <= 100
• grid[i][j] is either 0 or 1
• There are exactly two islands in the grid
Assumptions:
• The grid will always contain exactly two islands, so no edge cases with more or fewer islands are possible.
• The grid will not be empty and will always have a size of at least 2x2.
Input: Input: grid = [[1,0],[0,1]]
Explanation: In this example, there are two islands represented by 1's at positions (0,1) and (1,0). The minimum number of flips required to connect them is 1, flipping the 0 at position (0,0).

Input: Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Explanation: In this example, the two islands are at positions (0,0), (0,2), (2,0), and (2,2). The minimum number of flips required to connect them is 2, flipping the two 0's at positions (1,0) and (1,2).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus