To solve this problem, we can use a Depth-First Search (DFS) approach with backtracking. The idea is to explore all possible paths from the starting cell (0, 0) to the destination cell (n-1, n-1) while ensuring that we only move through open cells (1) and do not revisit any cell.
Here’s a step-by-step Python implementation:
def find_paths(maze):
if not maze or not maze[0]:
return -1
n = len(maze)
directions = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
visited = set()
paths = []
def is_valid(x, y):
return 0 <= x < n and 0 <= y < n and maze[x][y] == 1 and (x, y) not in visited
def backtrack(x, y, path):
if x == n - 1 and y == n - 1:
paths.append(path)
return
visited.add((x, y))
for move, (dx, dy) in directions.items():
nx, ny = x + dx, y + dy
if is_valid(nx, ny):
backtrack(nx, ny, path + move)
visited.remove((x, y))
if is_valid(0, 0):
backtrack(0, 0, "")
else:
return -1
return paths if paths else -1
# Example usage:
maze = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
print(find_paths(maze))
Explanation:
- Input Validation: First, we check if the maze is empty. If it is, we return
-1.
- Directions: We define the possible movements (
U, D, L, R) and their corresponding changes in coordinates.
- Visited Set: We use a set
visited to keep track of cells that have already been visited to avoid revisiting them.
- is_valid Function: This function checks if a cell is within the maze boundaries, is open (
1), and has not been visited.
- backtrack Function: This is the core DFS function. It explores all possible paths from the current cell
(x, y). If it reaches the destination (n-1, n-1), it adds the current path to the paths list. Otherwise, it continues exploring by recursively calling itself for each valid neighboring cell.
- Backtracking: After exploring a path, we remove the current cell from the
visited set to allow other paths to use it.
- Initial Call: We start the DFS from the starting cell
(0, 0) if it is valid. If not, we return -1.
- Return Result: Finally, we return the list of all possible paths. If no paths are found, we return
-1.
Example:
For the given maze:
[
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
The possible paths from (0, 0) to (2, 2) are:
Thus, the output will be:
['RRDD', 'DRRD']
If no path exists, the function will return -1.