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
Minimum number of moves to escape maze matrix in Python
Suppose we have a binary matrix, where 0 represents an empty cell, and 1 is a wall. Starting from the top left corner (0, 0), we need to find the minimum number of cells to reach the bottom right corner (R-1, C-1), where R is the number of rows and C is the number of columns. If no path exists, return -1.
This is a classic shortest path problem that can be solved using Breadth-First Search (BFS).
Problem Example
If the input matrix is like ?
| 0 | 0 | 0 | 1 | 0 |
| 0 | 0 | 1 | 1 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 1 | 1 | 0 | 0 | 0 |
Then the output will be 8 because we can select the optimal path as shown below ?
| 0 | 0 | 0 | 1 | 0 |
| 0 | 0 | 1 | 1 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 1 | 1 | 0 | 0 | 0 |
Algorithm Steps
To solve this problem, we follow these steps ?
- Initialize dimensions: R = number of rows, C = number of columns
- Create a queue with starting position (0, 0, 1) if matrix[0][0] is 0
- Mark the starting cell as visited by setting it to 1
- For each position (r, c, distance) in the queue:
- If we reached the destination (R-1, C-1), return the distance
- Explore all four directions: up, down, left, right
- For valid unvisited cells, mark as visited and add to queue
- If no path is found, return -1
Implementation
def solve(matrix):
R, C = len(matrix), len(matrix[0])
# Initialize queue with starting position if it's empty
q = [(0, 0, 1)] if matrix[0][0] == 0 else []
# Mark starting position as visited
if matrix[0][0] == 0:
matrix[0][0] = 1
# BFS traversal
for r, c, d in q:
# Check if we reached the destination
if (r, c) == (R - 1, C - 1):
return d
# Explore all four directions
for x, y in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
# Check bounds and if cell is empty
if 0 <= x < R and 0 <= y < C and matrix[x][y] == 0:
matrix[x][y] = 1 # Mark as visited
q.append((x, y, d + 1)) # Add to queue
return -1 # No path found
# Test with the example matrix
matrix = [
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 0]
]
result = solve(matrix)
print(f"Minimum moves required: {result}")
Minimum moves required: 8
How It Works
The algorithm uses BFS to guarantee finding the shortest path. The queue stores tuples of (row, column, distance), and we explore all reachable cells level by level. By marking visited cells as 1, we avoid revisiting them and ensure optimal pathfinding.
Edge Cases
The solution handles several edge cases ?
# Case 1: Starting position is blocked
blocked_start = [
[1, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
print("Blocked start:", solve([row[:] for row in blocked_start]))
# Case 2: No path exists
no_path = [
[0, 1, 0],
[1, 1, 0],
[0, 0, 0]
]
print("No path:", solve([row[:] for row in no_path]))
# Case 3: Direct path
direct = [
[0, 0],
[0, 0]
]
print("Direct path:", solve([row[:] for row in direct]))
Blocked start: -1 No path: -1 Direct path: 3
Time and Space Complexity
- Time Complexity: O(R × C) - In worst case, we visit all cells once
- Space Complexity: O(R × C) - Queue can store all cells in worst case
Conclusion
This BFS-based solution efficiently finds the minimum number of moves to escape a maze matrix. The algorithm guarantees the shortest path by exploring cells level by level, making it optimal for this type of pathfinding problem.
---