Home > OS >  python maze recursion problem, RecursionError: maximum recursion depth exceeded in comparison
python maze recursion problem, RecursionError: maximum recursion depth exceeded in comparison

Time:12-09

Hi i hope that someone can help me with this code, hardest code i have wrote, I need to use recursion to solve a maze, every value should be higher than the previous one these are examples : examples

idk why but there is a problem printing the answer of 5 questions and answers

def solve_maze_monotonic_helper(maze,index_x,index_y,last_value,lastvalue_list,final):
    if index_y == -1 or index_y ==len(maze) or index_x == -1 or index_x == len(maze[0]):
        return False
    if last_value < maze[index_y][index_x]:
        final.append(lastvalue_list)
    if last_value >= maze[index_y][index_x] and (index_x !=0 or index_y !=0):
        return False
    if (index_y == len(maze)-1) and (index_x == len(maze[0])-1):
        final.append([index_y,index_x])
        return final
    difference_y = index_y - lastvalue_list[0]
    difference_x = index_x - lastvalue_list[1]
    last_value =maze[index_y][index_x]
    lastvalue_list = [index_y,index_x]
    right,down,left,up =True,True,True,True
    right = solve_maze_monotonic_helper(maze,index_x 1,index_y,last_value,lastvalue_list,final)
    if right == False:
        down = solve_maze_monotonic_helper(maze,index_x,index_y 1,last_value,lastvalue_list,final)
    if down == False:
        left = solve_maze_monotonic_helper(maze,index_x-1,index_y,last_value,lastvalue_list,final)
    if left == False:
        up = solve_maze_monotonic_helper(maze,index_x,index_y-1,last_value,lastvalue_list,final)
    if up == False:
        final.pop(len(final)-1)
        return False
    return final

print(solve_maze_monotonic_helper([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 6]],0,0,1,[0,0],[]))

CodePudding user response:

if last_value >= maze[index_y][index_x] and (index_x !=0 or index_y !=0):
    return False

This line can create an endless loop, if you can't find a path with right->right or right->down the next move is right->left, back to (0,0) which will never be considered invalid causing the loop to just keep repeating, getting deeper and deeper into recursive calls until you hit the limit.

if last_value >= maze[index_y][index_x] should be enough if you fix the rest of the function

set last_value to a negative number to start with if you don't want it to be true at the first iteration.

  • Related