I've been trying to solve a maze using backtracking. The code uses multiple recursions:
def solve_maze(x,y):
if maze[x][y] == 'G': #checking if we've reached the target
solution[x][y] = 1
return True
if x>=0 and y>=0 and x<length and y<width and solution[x][y] == 0 and maze[x][y] == ' ':
solution[x][y] = 1
if solve_maze(x+1, y):
return True
if solve_maze(x, y+1):
return True
if solve_maze(x-1, y):
return True
if solve_maze(x, y-1):
return True
solution[x][y] = 0
return False
first time I executed the program, the "recursion limit exceeded" error showed up. To remedy that, I increased the limit:
sys.setrecursionlimit(10000)
Now that I run the program, Python crashes. What is happening? how can I solve this? Maze is not very big. its dimensions are 10*9:
maze = [['#'] * 10,
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', '#', ' ', '#', ' ', '#', ' ', ' ', '#'],
['#', ' ', '#', ' ', '#', '#', '#', ' ', '#', '#'],
['#', ' ', '#', '#', '#', '*', '#', ' ', ' ', '#'],
['#', ' ', '#', ' ', ' ', ' ', '#', '#', ' ', '#'],
['#', ' ', '#', ' ', '#', '#', '#', '#', ' ', '#'],
['G', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#'] * 10]
*this is added later: at the end of solve_maze definition there was this piece of code:
if solve_maze(x, y):
for i in solution:
print(i)
else:
print('no solution')
I noticed by removing it, the program works fine.Still have no clue why