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

标签 python

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

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
所以问题是要找出特定的汽车是否可以驶出 parking 场。
我的想法是用递归来解决,如下
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
如您所见,它无法正常工作,因为它会来回移动一辆车,直到达到最大递归深度。我不确定如何处理它,也许有一种方法可以枚举所有独特的网格并逐一检查它们。

最佳答案

确认一下,这是一款名为“高峰时间”的益智游戏的通用版本。
您需要将此视为图遍历问题。每个棋盘位置都是图的一个节点;一次移动表示两个节点之间的边。
您必须实现一种算法来遍历此图,搜索解决方案状态的路径。这是一个众所周知的范式;你有一些研究要做。要包含的关键部分是避免访问您已经看到的任何节点。这是避免任何循环的最简单方法。

关于Python回溯问题,达到最大递归深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64470855/

相关文章:

python - 检查页面加载 (Python)

python - Pandas 数据帧相等性测试

python - 查找文本列表并在匹配字段处替换

python - 将 unicode 字符编码为 un​​icode 转义序列

python - 监视文件夹中添加的 .jpg、使用 CUPS 自动打印、将相同的 .jpg 移动到另一个文件夹

python - 将字符串转换为有序字典?

python - Pandas 替换多个值

python - Python 程序员资源

python - 使用 Python ast 模块访问语法树中的节点

python - Flask_login 是否自动设置 "next"参数?