繁体   English   中英

Python回溯问题,达到最大递归深度

[英]Python backtracking problem, maximum recursion depth reached

给定一个m*n停车场,停车场有几辆车,每辆车如下:

car=[i,j,w,h,direction]
#i,j are top left position
#w,h are width and height
#direction can be -1/1 for horizontal/vertical
#horizontal cars can only move left or right
#vertical cars can only move up and down
#move one step at a time

在边缘或网格处有一个出口

exit=[i,j]
#i=0 or m-1
#j=0 or n-1

所以问题是要找出特定的汽车是否可以驶出停车场。 我的想法是用递归来解决,如下

grid=[[0]*n for _ in range(m)]

#use dict to store cars info
cars={'car0':[i,j,w,h,dir],'car1':[...],'target_car':[...]}

#and a function to determine if it's possible to move a car in a certain direction
#which will return True if I can move cars[car_name] one step to move_direction
#false otherwise
is_valid_move(car_name,move_direction)

#and I have a function to actually move the car if previous function return True
move_car(car_name,direction) 

and now here is the function to solve the problem
def solver(grid,cars):
    #base cases
    if (some basic conditions):
        return True or False based on condition
    
    #otherwise, we try to move one car at a time
    for car_name in cars.keys():
        if is_valid_move(car_name,direction):
            move_car(car_name,direction)
            if solver(gird,cars):
                return True
            #just recover the parking gird
            move_car(car_name,inverse_direction)
        if is_valid_move(car_name,inverse_direction):
            move_car(car_name,inverse_direction)
            if solver(gird,cars):
                return True
            #just recover the parking gird
            move_car(car_name,direction)
    return False

如您所见,它无法正常工作,因为它会来回移动一辆车,直到达到最大递归深度。 我不确定如何处理它,也许有一种方法可以枚举所有独特的网格并逐一检查它们。

确认一下,这是一款名为“高峰时间”的益智游戏的通用版本。

您需要将此视为图遍历问题。 每个棋盘位置都是图的一个节点; 一次移动表示两个节点之间的边。

您必须实现一种算法来遍历此图,搜索解决方案状态的路径。 这是一个众所周知的范式; 你有一些研究要做。 要包含的关键部分是避免访问您已经看到的任何节点。 这是避免任何循环的最简单方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM