bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 934. Shortest Bridge

934. Shortest Bridge

Leetcode Solutions

Depth-First-Search + Breadth-First-Search

  1. Iterate over the grid to find the first land cell of the first island.
  2. Use DFS starting from this cell to mark all connected land cells of the first island with a distinct value (e.g., 2).
  3. Initialize a BFS queue with all the marked cells of the first island.
  4. Perform BFS by expanding from the marked cells into water cells (0s), marking them as visited (e.g., -1) to avoid revisiting.
  5. If during BFS we encounter a cell of the second island (1), return the current distance as the result.
  6. If not, increment the distance and continue BFS with the new frontier of cells.
  7. Repeat steps 4-6 until the second island is reached.
UML Thumbnail

Breadth-First-Search

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...