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

Leetcode Problem 1730. Shortest Path to Get Food

1730. Shortest Path to Get Food

Leetcode Solutions

Breadth-First Search (BFS) for Shortest Path

  1. Find the starting position of the player (marked with '*') in the grid.
  2. Initialize a queue and add the starting position along with the initial step count (0).
  3. Initialize a set to keep track of visited cells.
  4. While the queue is not empty, perform the following steps: a. Dequeue the front cell from the queue and get its coordinates and step count. b. If the current cell is a food cell (marked with '#'), return the step count as the shortest path length. c. Otherwise, iterate over all possible directions (up, down, left, right). d. For each direction, calculate the coordinates of the adjacent cell. e. If the adjacent cell is within bounds, not an obstacle ('X'), and not visited, mark it as visited and enqueue it with an incremented step count.
  5. If no food cell is reachable, return -1.
UML Thumbnail

Depth-First Search (DFS) for Shortest Path

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...