简化程序的速度*

2024-04-26 04:07:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试优化我自己的A*搜索算法的实现有一段时间了,结果只是改变了实际的算法部分。你知道吗

我一直在想,这种方法是否比普通的A*更快。为什么,或者为什么不?如果是这样的话,有什么理由在这个稍有不同的方法上使用正则A*?你知道吗

def find_path(a, b):
    seen = set()
    opened = set()

    parent = {}
    distance = {a: path_distance(a, b)}

    while opened:
        node = min(opened, key=lambda x: distance[x])

        if node == end:
            path = []

            while node in parent:
                path.append(node)
                node = parent[node]

            return path

        opened.remove(node)

        for neighbor in node.neighbors:
            if neighbor not in seen:
                seen.add(neighbor)
                opened.add(neighbor)

                parent[neighbor] = node
                distance[neighbor] = pathDistance(neighbor, b)

def path_distance(a, b):
    return sum(y - x for x, y in zip(a.position, b.position))

我知道如何使用堆队列,但这不是这个问题的重点。你知道吗


Tags: path方法innodeforreturnifdef
1条回答
网友
1楼 · 发布于 2024-04-26 04:07:42

原稿有开集和闭集。它将检查邻居是否在闭集中,如果该暂定分数较高,则将跳过它。如果在开放集合中是而不是,或者暂定分数较低,它将使用该路径作为更好的路径。你知道吗

取而代之的是一个打开的集合和一个看到的集合。检查它是否而不是在seen集中,在这种情况下,您将把它添加到seen中,并使用它。你知道吗

这是非常不同的,很可能会给出不正确的结果。据我所知,你的算法不会产生最短路径,它总是使用最后一个邻居作为路径。你知道吗

相关问题 更多 >