![]() |
VOOZH | about |
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
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:
5