Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find Shortest distance from a guard in a Bankin Python
Suppose we have a matrix filled with three letters 'O', 'G', and 'W' where 'O' represents open space, 'G' represents guards, and 'W' represents walls in a bank. We need to replace all O's with their shortest distance from the nearest guard, without going through walls. In the output matrix, guards become 0 and walls become -1.
Problem Example
If the input matrix is:
| O | O | O | O | G |
| O | O | O | W | O |
| O | W | O | O | O |
| G | W | W | W | O |
| O | O | O | O | G |
The output will be:
| 3 | 3 | 2 | 1 | 0 |
| 2 | 3 | 3 | -1 | 1 |
| 1 | -1 | 4 | 3 | 2 |
| 0 | -1 | -1 | -1 | 1 |
| 1 | 2 | 2 | 1 | 0 |
Algorithm Approach
We use multi-source BFS (Breadth-First Search) to solve this problem efficiently:
- Initialize all guard positions with distance 0
- Add all guards to a queue simultaneously
- Use BFS to explore all reachable open spaces
- Calculate minimum distance from any guard to each open space
Implementation
from collections import deque
def find_shortest_distance(matrix):
if not matrix or not matrix[0]:
return []
M, N = len(matrix), len(matrix[0])
result = [[-1 for _ in range(N)] for _ in range(M)]
queue = deque()
# Direction vectors for up, right, down, left
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
# Initialize: Add all guards to queue and mark walls
for i in range(M):
for j in range(N):
if matrix[i][j] == 'G':
result[i][j] = 0
queue.append((i, j, 0)) # (row, col, distance)
elif matrix[i][j] == 'W':
result[i][j] = -1
# Multi-source BFS
while queue:
x, y, dist = queue.popleft()
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
# Check bounds and if cell is unvisited open space
if (0 <= new_x < M and 0 <= new_y < N and
matrix[new_x][new_y] == 'O' and result[new_x][new_y] == -1):
result[new_x][new_y] = dist + 1
queue.append((new_x, new_y, dist + 1))
return result
def print_matrix(matrix):
for row in matrix:
print(' '.join(map(str, row)))
# Test the solution
matrix = [['O', 'O', 'O', 'O', 'G'],
['O', 'O', 'O', 'W', 'O'],
['O', 'W', 'O', 'O', 'O'],
['G', 'W', 'W', 'W', 'O'],
['O', 'O', 'O', 'O', 'G']]
result = find_shortest_distance(matrix)
print_matrix(result)
3 3 2 1 0 2 3 3 -1 1 1 -1 4 3 2 0 -1 -1 -1 1 1 2 2 1 0
How It Works
The algorithm works in these steps:
- Initialization: Create result matrix, mark guards as distance 0, walls as -1
- Multi-source BFS: Start BFS from all guards simultaneously
- Distance Calculation: For each open space, calculate minimum distance to nearest guard
- Boundary Check: Ensure we stay within matrix bounds and only visit open spaces
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(M × N) | Visit each cell once |
| Space | O(M × N) | Result matrix and queue storage |
Conclusion
Multi-source BFS efficiently finds the shortest distance from guards to all open spaces in the bank matrix. The algorithm ensures optimal distance calculation by exploring all paths simultaneously from multiple guard positions.
