Skip to content

Commit 4cfceec

Browse files
Create RatInAMaze.py
1 parent dba8eec commit 4cfceec

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

backtracking/RatInAMaze.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
class Solution:
2+
def __init__(self):
3+
# Initialize a string direction which represents all the directions.
4+
self.direction = "DLRU"
5+
# Arrays to represent changes in rows and columns
6+
self.dr = [1, 0, 0, -1]
7+
self.dc = [0, -1, 1, 0]
8+
9+
# Function to check if cell (r, c) is inside the maze and unblocked
10+
def is_valid(self, r, c, n, maze):
11+
return 0 <= r < n and 0 <= c < n and maze[r] == 1
12+
13+
# Function to get all valid paths
14+
def solve(self, r, c, maze, n, ans, current_path):
15+
# If we reach the bottom right cell of the matrix, add the current path to ans and return
16+
if r == n - 1 and c == n - 1:
17+
ans.append(current_path)
18+
return
19+
20+
# Mark the current cell as blocked
21+
maze[r] = 0
22+
23+
for i in range(4):
24+
# Find the next row based on the current row (r) and the dr[] array
25+
nextr = r + self.dr[i]
26+
# Find the next column based on the current column (c) and the dc[] array
27+
nextc = c + self.dc[i]
28+
29+
# Check if the next cell is valid or not
30+
if self.is_valid(nextr, nextc, n, maze):
31+
current_path += self.direction[i]
32+
# Recursively call the solve function for the next cell
33+
self.solve(nextr, nextc, maze, n, ans, current_path)
34+
current_path = current_path[:-1]
35+
36+
# Mark the current cell as unblocked
37+
maze[r] = 1
38+
39+
def find_path(self, maze, n):
40+
# List to store all the valid paths
41+
ans = []
42+
43+
# Check if the top left cell is unblocked
44+
if maze[0][0] == 1:
45+
current_path = ""
46+
self.solve(0, 0, maze, n, ans, current_path)
47+
return ans
48+
49+
# Main function
50+
51+
52+
def main():
53+
n = 4
54+
55+
m = [
56+
[1, 0, 0, 0],
57+
[1, 1, 0, 1],
58+
[1, 1, 0, 0],
59+
[0, 1, 1, 1]
60+
]
61+
62+
obj = Solution()
63+
result = obj.find_path(m, n)
64+
65+
if not result:
66+
print(-1)
67+
else:
68+
for path in result:
69+
print(path, end=" ")
70+
print()
71+
72+
73+
if __name__ == "__main__":
74+
main()

0 commit comments

Comments
 (0)