# Find Shortest distance from a guard in a Bank

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.

Examples:

O ==> Open Space G ==> Guard W ==> WallInput:O O O O G O W W O O O O O W O G W W W O O O O O GOutput: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 –

## CPP

`// C++ program to replace all of the O's in the matrix ` `// with their shortest distance from a guard ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// store dimensions of the matrix ` `#define M 5 ` `#define N 5 ` ` ` `// An Data Structure for queue used in BFS ` `struct` `queueNode ` `{ ` ` ` `// i, j and distance stores x and y-coordinates ` ` ` `// of a matrix cell and its distance from guard ` ` ` `// respectively ` ` ` `int` `i, j, distance; ` `}; ` ` ` `// These arrays are used to get row and column ` `// numbers of 4 neighbors of a given cell ` `int` `row[] = { -1, 0, 1, 0}; ` `int` `col[] = { 0, 1, 0, -1 }; ` ` ` `// return true if row number and column number ` `// is in range ` `bool` `isValid(` `int` `i, ` `int` `j) ` `{ ` ` ` `if` `((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) ` ` ` `return` `false` `; ` ` ` ` ` `return` `true` `; ` `} ` ` ` `// return true if current cell is an open area and its ` `// distance from guard is not calculated yet ` `bool` `isSafe(` `int` `i, ` `int` `j, ` `char` `matrix[][N], ` `int` `output[][N]) ` `{ ` ` ` `if` `(matrix[i][j] != ` `'O'` `|| output[i][j] != -1) ` ` ` `return` `false` `; ` ` ` ` ` `return` `true` `; ` `} ` ` ` `// Function to replace all of the O's in the matrix ` `// with their shortest distance from a guard ` `void` `findDistance(` `char` `matrix[][N]) ` `{ ` ` ` `int` `output[M][N]; ` ` ` `queue<queueNode> q; ` ` ` ` ` `// finding Guards location and adding into queue ` ` ` `for` `(` `int` `i = 0; i < M; i++) ` ` ` `{ ` ` ` `for` `(` `int` `j = 0; j < N; j++) ` ` ` `{ ` ` ` `// initialize each cell as -1 ` ` ` `output[i][j] = -1; ` ` ` `if` `(matrix[i][j] == ` `'G'` `) ` ` ` `{ ` ` ` `queueNode pos = {i, j, 0}; ` ` ` `q.push(pos); ` ` ` `// guard has 0 distance ` ` ` `output[i][j] = 0; ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` ` ` `// do till queue is empty ` ` ` `while` `(!q.empty()) ` ` ` `{ ` ` ` `// get the front cell in the queue and update ` ` ` `// its adjacent cells ` ` ` `queueNode curr = q.front(); ` ` ` `int` `x = curr.i, y = curr.j, dist = curr.distance; ` ` ` ` ` `// do for each adjacent cell ` ` ` `for` `(` `int` `i = 0; i < 4; i++) ` ` ` `{ ` ` ` `// if adjacent cell is valid, has path and ` ` ` `// not visited yet, en-queue it. ` ` ` `if` `(isSafe(x + row[i], y + col[i], matrix, output) ` ` ` `&& isValid(x + row[i], y + col[i])) ` ` ` `{ ` ` ` `output[x + row[i]][y + col[i]] = dist + 1; ` ` ` ` ` `queueNode pos = {x + row[i], y + col[i], dist + 1}; ` ` ` `q.push(pos); ` ` ` `} ` ` ` `} ` ` ` ` ` `// dequeue the front cell as its distance is found ` ` ` `q.pop(); ` ` ` `} ` ` ` ` ` `// print output matrix ` ` ` `for` `(` `int` `i = 0; i < M; i++) ` ` ` `{ ` ` ` `for` `(` `int` `j = 0; j < N; j++) ` ` ` `cout << std::setw(3) << output[i][j]; ` ` ` `cout << endl; ` ` ` `} ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `char` `matrix[][N] = ` ` ` `{ ` ` ` `{` `'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'` `} ` ` ` `}; ` ` ` ` ` `findDistance(matrix); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python

`# Python3 program to replace all of the O's in the matrix ` `# with their shortest distance from a guard ` `from` `collections ` `import` `deque as queue ` ` ` `# store dimensions of the matrix ` `M ` `=` `5` `N ` `=` `5` ` ` ` ` `# These arrays are used to get row and column ` `# numbers of 4 neighbors of a given cell ` `row ` `=` `[` `-` `1` `, ` `0` `, ` `1` `, ` `0` `] ` `col ` `=` `[` `0` `, ` `1` `, ` `0` `, ` `-` `1` `] ` ` ` `# return true if row number and column number ` `# is in range ` `def` `isValid(i, j): ` ` ` `if` `((i < ` `0` `or` `i > M ` `-` `1` `) ` `or` `(j < ` `0` `or` `j > N ` `-` `1` `)): ` ` ` `return` `False` ` ` ` ` `return` `True` ` ` `# return true if current cell is an open area and its ` `# distance from guard is not calculated yet ` `def` `isSafe(i, j,matrix, output): ` ` ` ` ` `if` `(matrix[i][j] !` `=` `'O'` `or` `output[i][j] !` `=` `-` `1` `): ` ` ` `return` `False` ` ` ` ` `return` `True` ` ` `# Function to replace all of the O's in the matrix ` `# with their shortest distance from a guard ` `def` `findDistance(matrix): ` ` ` `output ` `=` `[[ ` `-` `1` `for` `i ` `in` `range` `(N)]` `for` `i ` `in` `range` `(M)] ` ` ` `q ` `=` `queue() ` ` ` ` ` `# finding Guards location and adding into queue ` ` ` `for` `i ` `in` `range` `(M): ` ` ` `for` `j ` `in` `range` `(N): ` ` ` ` ` `# initialize each cell as -1 ` ` ` `output[i][j] ` `=` `-` `1` ` ` `if` `(matrix[i][j] ` `=` `=` `'G'` `): ` ` ` `pos ` `=` `[i, j, ` `0` `] ` ` ` `q.appendleft(pos) ` ` ` ` ` `# guard has 0 distance ` ` ` `output[i][j] ` `=` `0` ` ` ` ` ` ` ` ` `# do till queue is empty ` ` ` `while` `(` `len` `(q) > ` `0` `): ` ` ` ` ` `# get the front cell in the queue and update ` ` ` `# its adjacent cells ` ` ` `curr ` `=` `q.pop() ` ` ` `x, y, dist ` `=` `curr[` `0` `], curr[` `1` `], curr[` `2` `] ` ` ` ` ` `# do for each adjacent cell ` ` ` `for` `i ` `in` `range` `(` `4` `): ` ` ` ` ` `# if adjacent cell is valid, has path and ` ` ` `# not visited yet, en-queue it. ` ` ` ` ` `if` `isValid(x ` `+` `row[i], y ` `+` `col[i]) ` `and` `isSafe(x ` `+` `row[i], y ` `+` `col[i], matrix, output) : ` ` ` `output[x ` `+` `row[i]][y ` `+` `col[i]] ` `=` `dist ` `+` `1` ` ` ` ` `pos ` `=` `[x ` `+` `row[i], y ` `+` `col[i], dist ` `+` `1` `] ` ` ` `q.appendleft(pos) ` ` ` ` ` `# proutput matrix ` ` ` ` ` `for` `i ` `in` `range` `(M): ` ` ` `for` `j ` `in` `range` `(N): ` ` ` `if` `output[i][j] > ` `0` `: ` ` ` `print` `(output[i][j], end` `=` `" "` `) ` ` ` `else` `: ` ` ` `print` `(output[i][j],end` `=` `" "` `) ` ` ` `print` `() ` ` ` ` ` `# Driver code ` ` ` `matrix ` `=` `[[` `'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'` `]] ` ` ` `findDistance(matrix) ` ` ` `# This code is contributed by mohit kumar 29 ` |

*chevron_right*

*filter_none*

**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

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 contribute@geeksforgeeks.org. 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.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

## Recommended Posts:

- Find the shortest distance between any pair of two different good nodes
- Shortest distance between two cells in a matrix or grid
- Find shortest safe route in a path with landmines
- Find count of pair of nodes at even distance
- Find integral points with minimum distance from given set of integers using BFS
- Shortest Path Faster Algorithm
- Multistage Graph (Shortest Path)
- Shortest Path using Meet In The Middle
- Shortest path in an unweighted graph
- Shortest path in a Binary Maze
- Some interesting shortest path questions | Set 1
- Dijkstra’s shortest path algorithm using set in STL
- Shortest paths from all vertices to a destination
- Shortest Path in Directed Acyclic Graph
- Dijkstra's Shortest Path Algorithm using priority_queue of STL
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Shortest cycle in an undirected unweighted graph
- Johnson's algorithm for All-pairs shortest paths
- Dijkstra's shortest path with minimum edges
- Shortest Path with even number of Edges from Source to Destination