From 0fef1b0c5e62dcd5cf634e68c6d4a9a14c2d826a Mon Sep 17 00:00:00 2001 From: JASKAMAL SINGH <54163864+JASKAMAL22@users.noreply.github.com> Date: Wed, 5 Oct 2022 16:04:46 +0530 Subject: [PATCH] Create Rat_in_a_Maze.py Added python source code --- Backtracking/Rat_in_a_Maze.py | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Backtracking/Rat_in_a_Maze.py diff --git a/Backtracking/Rat_in_a_Maze.py b/Backtracking/Rat_in_a_Maze.py new file mode 100644 index 0000000..829267f --- /dev/null +++ b/Backtracking/Rat_in_a_Maze.py @@ -0,0 +1,69 @@ +# Maze size +N = 4 + +def printSolution( sol ): + + for i in sol: + for j in i: + print(str(j) + " ", end ="") + print("") + +def isSafe( maze, x, y ): + if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: + return True + + return False + +def solveMaze( maze ): + # Creating a 4 * 4 2-D list + sol = [ [ 0 for j in range(4) ] for i in range(4) ] + + if solveMazeUtil(maze, 0, 0, sol) == False: + print("Solution doesn't exist"); + return False + printSolution(sol) + return True + +def solveMazeUtil(maze, x, y, sol): + # if (x, y is goal) return True + if x == N - 1 and y == N - 1: + sol[x][y] = 1 + return True + + # Check if maze[x][y] is valid + if isSafe(maze, x, y) == True: + # mark x, y as part of solution path + sol[x][y] = 1 + + # Move forward in x direction + if solveMazeUtil(maze, x + 1, y, sol) == True: + return True + + # If moving in x direction doesn't give solution + # then Move down in y direction + if solveMazeUtil(maze, x, y + 1, sol) == True: + return True + + # If none of the above movements work then + # BACKTRACK: unmark x, y as part of solution path + sol[x][y] = 0 + return False + +# Main Program +if __name__ == "__main__": + # Initialising the maze + maze = [ [1, 0, 0, 0], + [1, 1, 0, 1], + [0, 1, 0, 0], + [1, 1, 1, 1] ] + + solveMaze(maze) +''' +============== +Output: +1 0 0 0 +1 1 0 0 +0 1 0 0 +0 1 1 1 +============== +'''