VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-path-to-get-food-in-matrix/

⇱ Shortest Path to Get Food in Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest Path to Get Food in Matrix

Last Updated : 18 Apr, 2024

Given a matrix grid[][], where '*' represents your location, '#' represents food cells, 'O' represents free space, 'X' represents obstacles. The task is to find the shortest path from your location to any food cell in a given matrix grid, Return the length of the shortest path to reach any food cell, or -1 if no path exists.

Example:

Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]]
Output: 3
Explanation: only 3 steps needed o reach the food.

Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
Output: -1
Explanation: Not possible to reach the food.

Approach:

The idea is to use multi-source Breadth-First Search (BFS) algorithm. Starts the BFS from the given location and explores the neighbor nodes at the present depth prior to moving on to nodes at the next depth level.

This property of BFS is useful in this problem because it guarantees that we explore all cells at a given distance before moving on to the cells at the next distance. Therefore, the first time we reach a food cell, we can be sure that we have found the shortest path.

Steps-by-step approach:

  • Initialize a queue (Q) to keep track of cells to visit.
  • Map grid values ('*', '#', 'O') to integers (1, 2, 3) for better handling.
  • Find the starting points marked by '*' and add it to the queue.
  • Perform a Breadth-First Search (BFS) traversal of the grid using the queue.
  • For each cell popped from the queue:
    • If it's a food cell ('#'), update the shortest path length and exit the BFS loop.
    • If it's an empty space ('O'), mark it as visited and continue exploring neighboring cells.
    • Use a priority queue to ensure food cells are explored first.
  • At the end of BFS, return the length of the shortest path to reach any food cell. If no path exists, return -1.

Below are the implementation of the above approach:


Output
3

Time complexity: O(N*M), where N and M are the number of rows and columns in the given matrix
Auxiliary Space: O(N*M)


Comment
Article Tags:
Article Tags: