Skip to content

Commit 913c90a

Browse files
authored
Create rat_in_a_maze.py
1 parent 2df824d commit 913c90a

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def is_safe(maze, x, y, n):
2+
return 0 <= x < n and 0 <= y < n and maze[x][y] == 1
3+
4+
def solve_maze_util(maze, x, y, n, solution):
5+
if x == n - 1 and y == n - 1:
6+
solution[x][y] = 1
7+
return True
8+
if is_safe(maze, x, y, n):
9+
solution[x][y] = 1
10+
if solve_maze_util(maze, x + 1, y, n, solution):
11+
return True
12+
if solve_maze_util(maze, x, y + 1, n, solution):
13+
return True
14+
solution[x][y] = 0
15+
return False
16+
return False
17+
18+
def solve_maze(maze, n):
19+
solution = [[0] * n for _ in range(n)]
20+
if not solve_maze_util(maze, 0, 0, n, solution):
21+
print("No solution exists")
22+
return
23+
for row in solution:
24+
print(*row)
25+
26+
if __name__ == "__main__":
27+
n = int(input())
28+
maze = [list(map(int, input().split())) for _ in range(n)]
29+
solve_maze(maze, n)

0 commit comments

Comments
 (0)