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

Leetcode Problem 1091. Shortest Path in Binary Matrix

1091. Shortest Path in Binary Matrix

Leetcode Solutions

Breadth-first Search (BFS)

  1. Check if the starting cell (0, 0) is blocked (contains a 1); if so, return -1.
  2. Initialize a queue to hold cells to explore and enqueue the starting cell with a distance of 1.
  3. While the queue is not empty: a. Dequeue the front cell from the queue. b. If the cell is the bottom-right cell, return the distance. c. Otherwise, iterate over all 8 possible directions from the current cell. d. For each direction, check if the neighbor cell is within bounds, open, and unvisited. e. If valid, mark the neighbor as visited, record the distance, and enqueue it.
  4. If the queue is empty and the bottom-right cell has not been reached, return -1.
UML Thumbnail

Depth-first Search (DFS)

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...