27. Find shortest safe route in a matrix
The problem can be found at the following link: Question Link
My Approach
We start by identifying all the bomb locations in the matrix and mark their adjacent cells as unsafe.
Then, we perform a breadth-first search (BFS) starting from all the cells in the first column, considering them as starting points. During BFS traversal, we mark visited cells as unsafe and continue BFS.
We repeat BFS until we reach the last column or there are no more reachable safe cells.
The shortest path will be the minimum number of steps required to reach any cell in the last column from the starting points.
Time and Auxiliary Space Complexity
Time Complexity:
O(M * N)
, where M is the number of rows and N is the number of columns in the matrix. This complexity arises from the BFS traversal.Auxiliary Space Complexity:
O(M * N)
, where M is the number of rows and N is the number of columns in the matrix. This space is required for the queue used in BFS and for marking visited cells.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated