Skip to content

Commit cc97f30

Browse files
authored
Merge pull request #120 from JASKAMAL22/rat_in_a_maze
Rat_in_a_Maze
2 parents f2c1b97 + 0fef1b0 commit cc97f30

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Backtracking/Rat_in_a_Maze.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Maze size
2+
N = 4
3+
4+
def printSolution( sol ):
5+
6+
for i in sol:
7+
for j in i:
8+
print(str(j) + " ", end ="")
9+
print("")
10+
11+
def isSafe( maze, x, y ):
12+
if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
13+
return True
14+
15+
return False
16+
17+
def solveMaze( maze ):
18+
# Creating a 4 * 4 2-D list
19+
sol = [ [ 0 for j in range(4) ] for i in range(4) ]
20+
21+
if solveMazeUtil(maze, 0, 0, sol) == False:
22+
print("Solution doesn't exist");
23+
return False
24+
printSolution(sol)
25+
return True
26+
27+
def solveMazeUtil(maze, x, y, sol):
28+
# if (x, y is goal) return True
29+
if x == N - 1 and y == N - 1:
30+
sol[x][y] = 1
31+
return True
32+
33+
# Check if maze[x][y] is valid
34+
if isSafe(maze, x, y) == True:
35+
# mark x, y as part of solution path
36+
sol[x][y] = 1
37+
38+
# Move forward in x direction
39+
if solveMazeUtil(maze, x + 1, y, sol) == True:
40+
return True
41+
42+
# If moving in x direction doesn't give solution
43+
# then Move down in y direction
44+
if solveMazeUtil(maze, x, y + 1, sol) == True:
45+
return True
46+
47+
# If none of the above movements work then
48+
# BACKTRACK: unmark x, y as part of solution path
49+
sol[x][y] = 0
50+
return False
51+
52+
# Main Program
53+
if __name__ == "__main__":
54+
# Initialising the maze
55+
maze = [ [1, 0, 0, 0],
56+
[1, 1, 0, 1],
57+
[0, 1, 0, 0],
58+
[1, 1, 1, 1] ]
59+
60+
solveMaze(maze)
61+
'''
62+
==============
63+
Output:
64+
1 0 0 0
65+
1 1 0 0
66+
0 1 0 0
67+
0 1 1 1
68+
==============
69+
'''

0 commit comments

Comments
 (0)