【发布时间】:2016-06-18 13:17:17
【问题描述】:
我的 a* 算法并不总是采用最短路径。
在这张图片中,机器人必须穿过黑色方块,河流和树木是障碍物。黑线是它走过的路径,这显然不是最短的路径,因为它不应该下降。
这是我的 a* 代码和我正在使用的启发式算法:
def HeuristicCostEstimate(start, goal):
(x1, y1) = start
(x2, y2) = goal
return abs(x1 - x2) + abs(y1 - y2)
def AStar(grid, start, goal):
entry = 1
openSet = []
heappush(openSet,(1, entry, start))
cameFrom = {}
currentCost = {}
cameFrom[tuple(start)] = None
currentCost[tuple(start)] = 0
while not openSet == []:
current = heappop(openSet)[2]
print(current)
if current == goal:
break
for next in grid.Neighbours(current):
newCost = currentCost[tuple(current)] + grid.Cost(current, next)
if tuple(next) not in currentCost or newCost < currentCost[tuple(next)]:
currentCost[tuple(next)] = newCost
priority = newCost + HeuristicCostEstimate(goal, next)
entry +=1
heappush(openSet,(priority, entry, next))
cameFrom[tuple(next)] = current
return cameFrom, current
感谢您的帮助!并随时要求我澄清任何事情。
编辑:通过返回 0 删除启发式解决了这个问题。这表明问题出在我的启发式上。有谁知道是什么原因造成的吗?
【问题讨论】:
-
将您的代码粘贴到您的问题中。要使其成为代码块,请将其突出显示并按 Ctrl+k。
-
代码太多了,不能指望别人帮你调试。
-
谢谢大家,我现在已经用相关代码编辑了。
-
我不明白为什么如果它必须走在黑色方块上,这不是最短路径
-
如果您的启发式算法可以高估成本,那么它是“不可接受的”并且可能导致 A* 找不到最短路径。尝试构建一个测试夹具来计算实际的最短路径,并将其与您的启发式进行比较。
标签: python algorithm shortest-path a-star