Certainly! Here's a detailed explanation and a Python solution for the problem:
Problem Restatement:
You have an n x n binary matrix (maze) where:
1 means the cell is open.
0 means the cell is blocked.
A rat starts at the top-left corner (0, 0) and wants to reach the bottom-right corner (n-1, n-1).
The rat can move in four directions:
- Up (U)
- Down (D)
- Left (L)
- Right (R)
Constraints:
- The rat cannot visit the same cell more than once.
- The rat can only move through cells with value
1.
Goal:
Return all possible paths from (0, 0) to (n-1, n-1) as strings of directions. If no path exists, return -1.
Approach:
-
Backtracking / DFS:
- Start from
(0, 0).
- At each step, try moving in all four directions if:
- The next cell is inside the maze.
- The next cell is open (
1).
- The next cell is not visited yet.
- Mark the current cell as visited before moving.
- If you reach
(n-1, n-1), record the path.
- Backtrack by unmarking the current cell as visited after exploring all directions.
-
Data Structures:
- Use a
visited matrix to keep track of visited cells.
- Use a string to keep track of the path directions.
-
Return:
- If no path is found, return
-1.
- Otherwise, return all paths sorted lexicographically (optional but common in such problems).
Code Implementation:
def findPaths(maze):
n = len(maze)
if maze[0][0] == 0 or maze[n-1][n-1] == 0:
return -1 # No path if start or end is blocked
directions = [('D', 1, 0), ('L', 0, -1), ('R', 0, 1), ('U', -1, 0)]
# You can change order of directions if you want paths in a specific order
visited = [[False]*n for _ in range(n)]
paths = []
def is_valid(x, y):
return 0 <= x < n and 0 <= y < n and maze[x][y] == 1 and not visited[x][y]
def backtrack(x, y, path):
if x == n-1 and y == n-1:
paths.append(path)
return
visited[x][y] = True
for dir_char, dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid(nx, ny):
backtrack(nx, ny, path + dir_char)
visited[x][y] = False
backtrack(0, 0, "")
if not paths:
return -1
return sorted(paths)
# Example usage:
maze = [
[1, 0, 0, 0],
[1, 1, 0, 1],
[1, 1, 0, 0],
[0, 1, 1, 1]
]
print(findPaths(maze))
Explanation of the example:
For the given maze:
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1
- The rat starts at
(0,0).
- It tries to move down, left, right, up (in that order).
- It explores all valid paths without revisiting cells.
- Finally, it returns all possible paths as strings like
"DDRDRR".
Complexity:
- Time complexity: Exponential in the worst case, as it explores all possible paths.
- Space complexity: O(n^2) for the visited matrix and recursion stack.
If you want me to explain or modify the code further, just ask!