I need a Python code for backtracking. I have a robot car and I am trying to mak
ID: 3714762 • Letter: I
Question
I need a Python code for backtracking.
I have a robot car and I am trying to make it so that when it moves forward left or right it will record that information. It also records when it has decisions to make and saves it as a "checkpoint". When it reaches a dead end it will back track and go to the last point where it had a decision to make and not take the path again.
The code can just be the general lay out and I can fill in the exact command myself.
Something like this But in Python:
https://www.geeksforgeeks.org/backttracking-set-2-rat-in-a-maze/
Explanation / Answer
SIZE = 5
#Maze Prb
maze = [
[0,1,0,1,1],
[0,0,0,0,0],
[1,0,1,0,1],
[0,0,1,0,0],
[1,0,0,1,0]
]
#List for storing solution matrix
solution = [[0]*SIZE for _ in range(SIZE)]
#Solving maze using backtracking
def solution_maze(r, c):
if (r==SIZE-1) and (c==SIZE-1):
solution[r][c] = 1;
return True;
if r>=0 and c>=0 and r<SIZE and c<SIZE and solution[r][c] == 0 and maze[r][c] == 0:
#Safe
solution[r][c] = 1
#Down
if solution_maze(r+1, c):
return True
#Right
if solution_maze(r, c+1):
return True
#Up
if solution_maze(r-1, c):
return True
#Left
if solution_maze(r, c-1):
return True
#backtracking
solution[r][c] = 0;
return False;
return 0;
if(solution_maze(0,0)):
for i in solution:
print (i)
else:
print ("No solution")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.