0
Leetcode Problem 934. Shortest Bridge
934. Shortest Bridge
AI Mock Interview
Leetcode Solutions
Depth-First-Search + Breadth-First-Search
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Iterate over the grid to find the first land cell of the first island.
Use DFS starting from this cell to mark all connected land cells of the first island with a distinct value (e.g.,
2
).
Initialize a BFS queue with all the marked cells of the first island.
Perform BFS by expanding from the marked cells into water cells (
0
s), marking them as visited (e.g.,
-1
) to avoid revisiting.
If during BFS we encounter a cell of the second island (
1
), return the current distance as the result.
If not, increment the distance and continue BFS with the new frontier of cells.
Repeat steps 4-6 until the second island is reached.
Breadth-First-Search
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...