Python-加快A Star Pathfinding算法的速度
问题内容:
我已经编写了第一个稍微复杂的算法,即A Star
Pathfinding
算法的实现。我遵循了有关实现图形的一些Python.org建议,因此字典也包含每个节点都链接的所有节点。现在,由于这一切都是针对游戏的,因此每个节点实际上只是节点网格中的一个图块,因此,我将如何设计启发式方法以及偶尔对它们的引用。
多亏了timeit,我知道我每秒可以成功运行此功能一百次以上。可以理解的是,这让我有些不安,这没有任何其他“游戏内容”的发生,例如图形或计算游戏逻辑。所以,我很想看看你们中的任何人是否可以加快我的算法,我完全不熟悉Cython还是它的亲戚,我不能编写C语言行。
不用多说,这是我的A Star功能。
def aStar(self, graph, current, end):
openList = []
closedList = []
path = []
def retracePath(c):
path.insert(0,c)
if c.parent == None:
return
retracePath(c.parent)
openList.append(current)
while len(openList) is not 0:
current = min(openList, key=lambda inst:inst.H)
if current == end:
return retracePath(current)
openList.remove(current)
closedList.append(current)
for tile in graph[current]:
if tile not in closedList:
tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10
if tile not in openList:
openList.append(tile)
tile.parent = current
return path
问题答案:
一种简单的优化方法是使用集而不是打开集和封闭集的列表。
openSet = set()
closedSet = set()
这将使所有in
和not in
测试成为O(1)而不是O( n )。