Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’ represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix with their shortest distance from a guard, without being able to go through any walls. Also, replace the guards with 0 and walls with -1 in output matrix.
Expected Time complexity is O(MN) for a M x N matrix.
O ==> Open Space G ==> Guard W ==> Wall Input: O O O O G O W W O O O O O W O G W W W O O O O O G Output: 3 3 2 1 0 2 -1 -1 2 1 1 2 3 -1 2 0 -1 -1 -1 1 1 2 2 1 0
The idea is to do BFS. We first enqueue all cells containing the guards and loop till queue is not empty. For each iteration of the loop, we dequeue the front cell from the queue and for each of its four adjacent cells, if cell is an open area and its distance from guard is not calculated yet, we update its distance and enqueue it. Finally after BFS procedure is over, we print the distance matrix.
Below are implementation of above idea –
3 3 2 1 0 2 -1 -1 2 1 1 2 3 -1 2 0 -1 -1 -1 1 1 2 2 1 0
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the shortest distance between any pair of two different good nodes
- Shortest distance between two cells in a matrix or grid
- Sum of shortest distance on source to destination and back having at least a common vertex
- Find shortest safe route in a path with landmines
- Create a Graph by connecting divisors from N to M and find shortest path
- Dijkstra's shortest path algorithm | Greedy Algo-7
- Shortest Path in Directed Acyclic Graph
- Johnson's algorithm for All-pairs shortest paths
- Some interesting shortest path questions | Set 1
- Shortest path with exactly k edges in a directed and weighted graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Dijkstra’s shortest path algorithm using set in STL
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- Print shortest path to print a string on screen
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Multistage Graph (Shortest Path)
- Shortest Path Faster Algorithm
- Shortest path to reach one prime to other by changing single digit at a time
- Probabilistic shortest path routing algorithm for optical networks