gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:43:01 24 4
gpt4 key购买 nike

给定一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com