VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-distance-two-cells-matrix-grid/

⇱ Shortest distance between two cells in a matrix or grid - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest distance between two cells in a matrix or grid

Last Updated : 13 May, 2025

Given a 2D matrix mat[][] of size n × m. The task is to find the shortest distance from a source cell ('s') to a destination cell ('d'), by only moving through valid cells ('*'). We are not allowed to move through '0' cells, and movement is restricted to the four directions: up, down, left, and right. If it is not possible to reach, return -1.
Note: Only one source and one destination can be assumed in the input matrix.

Examples: 

Input: mat[][] = [[ '0', '*', '0', 's' ],
[ '*', '*', '*', '*' ],
[ '0', '*', '0', '*' ],
[ '*', 'd', '*', '*' ]]
Output: 5
Explanation: One of the shortest path is: (0,3) -> (1,3) -> (1,2) -> (1,1) -> (2,1) -> (3,1). Total steps = 5.

Input: mat[][] = [ [ '0', '*', '0', 's' ],
[ '*', '0', '*', '0' ],
[ '0', '*', '0', '*' ],
[ 'd', '*', '*', '*' ] ]
Output: -1
Explanation: No path exists from 's' to 'd' due to blocked cells ('0').

Input: mat[][] = [[ 's', '*', '*', '*' ],
[ 'd', '0', '*', '0' ]]
Output: 1

Using Breadth First Search - O(n*m) Time and O(n*m) Space 

The idea is to use Breadth-First Search (BFS) to explore the matrix level by level to find the shortest path from 's' (source) to 'd' (destination). The thought process is that BFS guarantees the shortest path in an unweighted grid, making it ideal for this problem. We use a queue to track the current cell and distance, and a visited matrix to avoid revisiting cells.

Steps to implement the above idea:

  • Create a visited matrix of the same size as input to keep track of visited cells.
  • Traverse the matrix to find the source 's', mark it visited and add it to the queue with distance 0.
  • While the queue is not empty, extract the current cell and check if it is the destination 'd'.
  • For each of the four directions, compute the new cell, and if it’s valid, add it to the queue with distance +1.
  • If destination is never reached after BFS ends, return -1 to indicate no valid path exists.

Output
5
Comment
Article Tags:
Article Tags: