维基百科 A* 寻路算法需要大量时间

发布于 2024-10-15 02:08:31 字数 3017 浏览 2 评论 0原文

我已经在 C# 中成功实现了 A* 寻路,但速度非常慢,我不明白为什么。我什至尝试不对 openNodes 列表进行排序,但它仍然是相同的。

地图大小为80x80,有10-11个节点。

我从这里获取了伪代码 Wikipedia

这是我的实现:

 public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd)
    {
        mMap.ClearNodes();

        mMap.GetTile(mStart.X, mStart.Y).Value = 0;
        mMap.GetTile(mEnd.X, mEnd.Y).Value = 0;

        List<PGNode> openNodes = new List<PGNode>();
        List<PGNode> closedNodes = new List<PGNode>();
        List<PGNode> solutionNodes = new List<PGNode>();

        mStart.G = 0;
        mStart.H = GetManhattanHeuristic(mStart, mEnd);

        solutionNodes.Add(mStart);
        solutionNodes.Add(mEnd);

        openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list.

        while (openNodes.Count > 0) // 2) Repeat the following:
        {
            openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F));

            PGNode current = openNodes[0]; // a) We refer to this as the current square.)

            if (current == mEnd)
            {
                while (current != null)
                {
                    solutionNodes.Add(current);
                    current = current.Parent;
                }

                return solutionNodes;
            }

            openNodes.Remove(current);
            closedNodes.Add(current); // b) Switch it to the closed list.

            List<PGNode> neighborNodes = current.GetNeighborNodes();
            double cost = 0;
            bool isCostBetter = false;

            for (int i = 0; i < neighborNodes.Count; i++)
            {
                PGNode neighbor = neighborNodes[i];
                cost = current.G + 10;
                isCostBetter = false;

                if (neighbor.Passable == false || closedNodes.Contains(neighbor))
                    continue; // If it is not walkable or if it is on the closed list, ignore it.

                if (openNodes.Contains(neighbor) == false)
                {
                    openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list.
                    isCostBetter = true;
                }
                else if (cost < neighbor.G)
                {
                    isCostBetter = true;
                }

                if (isCostBetter)
                {
                    neighbor.Parent = current; //  Make the current square the parent of this square. 
                    neighbor.G = cost;
                    neighbor.H = GetManhattanHeuristic(current, neighbor);
                }
            }
        }

        return null;
    }

这是我的启发式正在使用:

    private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd)
    {
        return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y);
    }

我做错了什么?一整天我都在看同样的代码。

I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same.

The map is 80x80, and there are 10-11 nodes.

I took the pseudocode from here Wikipedia

And this is my implementation:

 public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd)
    {
        mMap.ClearNodes();

        mMap.GetTile(mStart.X, mStart.Y).Value = 0;
        mMap.GetTile(mEnd.X, mEnd.Y).Value = 0;

        List<PGNode> openNodes = new List<PGNode>();
        List<PGNode> closedNodes = new List<PGNode>();
        List<PGNode> solutionNodes = new List<PGNode>();

        mStart.G = 0;
        mStart.H = GetManhattanHeuristic(mStart, mEnd);

        solutionNodes.Add(mStart);
        solutionNodes.Add(mEnd);

        openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list.

        while (openNodes.Count > 0) // 2) Repeat the following:
        {
            openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F));

            PGNode current = openNodes[0]; // a) We refer to this as the current square.)

            if (current == mEnd)
            {
                while (current != null)
                {
                    solutionNodes.Add(current);
                    current = current.Parent;
                }

                return solutionNodes;
            }

            openNodes.Remove(current);
            closedNodes.Add(current); // b) Switch it to the closed list.

            List<PGNode> neighborNodes = current.GetNeighborNodes();
            double cost = 0;
            bool isCostBetter = false;

            for (int i = 0; i < neighborNodes.Count; i++)
            {
                PGNode neighbor = neighborNodes[i];
                cost = current.G + 10;
                isCostBetter = false;

                if (neighbor.Passable == false || closedNodes.Contains(neighbor))
                    continue; // If it is not walkable or if it is on the closed list, ignore it.

                if (openNodes.Contains(neighbor) == false)
                {
                    openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list.
                    isCostBetter = true;
                }
                else if (cost < neighbor.G)
                {
                    isCostBetter = true;
                }

                if (isCostBetter)
                {
                    neighbor.Parent = current; //  Make the current square the parent of this square. 
                    neighbor.G = cost;
                    neighbor.H = GetManhattanHeuristic(current, neighbor);
                }
            }
        }

        return null;
    }

Here's the heuristic I'm using:

    private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd)
    {
        return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y);
    }

What am I doing wrong? It's an entire day I keep looking at the same code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

誰ツ都不明白 2024-10-22 02:08:31

首先,使用分析器。用工具告诉你什么是慢;缓慢的事情常常令人惊讶。并使用调试器。制作一个包含五个节点的地图,并在尝试查找路径时逐步执行代码的每一行。有什么意外发生吗?如果是这样,请弄清楚发生了什么事。

其次,撇开你的性能问题不谈,我认为你还存在正确性问题。您能向我们解释一下为什么您认为曼哈顿距离是一个合理的启发式吗?

(对于那些不熟悉该度量标准的读者来说,“曼哈顿距离”或“出租车距离”是如果您居住在网格上的城市中,您必须行驶的两点之间的距离。也就是说,向东北方向行驶 14 英里,您必须向北行驶 10 英里,然后向东行驶 10 英里,总共 20 英里。)

A* 算法的正确性要求启发式总是低估实际距离需要在两点之间行驶。如果图中存在任何“对角捷径”街道,则曼哈顿距离高估这些路径上的距离,因此算法不一定会找到最短路径

您为什么不使用欧几里德距离作为您的启发式?

您是否尝试过使用“始终为零”作为启发式的算法?这肯定是被低估的。 (这样做可以为您提供 Dijkstra 算法的实现。)

第三,您似乎在此实现中进行了大量排序。当然你可以使用优先级队列;这比排序便宜得多。

第四,我的博客上有一个 C# 3 中 A* 的实现,欢迎您使用;没有明示或暗示的保证,使用风险由您自行承担。

http://blogs.msdn.com/b/ericlippert/archive/tags/astar/

我的代码非常简单;我的实现中的算法如下所示:

var closed = new HashSet<Node>();
var queue = new PriorityQueue<double, Path<Node>>();
queue.Enqueue(0, new Path<Node>(start));
while (!queue.IsEmpty)
{
    var path = queue.Dequeue();
    if (closed.Contains(path.LastStep)) continue;
    if (path.LastStep.Equals(destination)) return path;
    closed.Add(path.LastStep);
    foreach(Node n in path.LastStep.Neighbours)
    {
        double d = distance(path.LastStep, n);
        var newPath = path.AddStep(n, d);
        queue.Enqueue(newPath.TotalCost + estimate(n), newPath);
    }
}

这个想法是我们维护一个路径优先级队列;也就是说,路径队列总是能够以最小的距离告诉您迄今为止的路径。然后我们检查是否已到达目的地;如果是这样,我们就完成了。如果没有,那么我们会根据(低估)到目标的距离将一堆新路径排入队列。

第五,维基百科中的伪代码可以改进。事实上,我的实际代码在很多方面都比伪代码更容易理解,这表明伪代码中可能有太多细节。

First off, use a profiler. Use tools to tell you what is slow; it is often surprising what is slow. And use a debugger. Make a map with five nodes in it and step through every line of the code as it tries to find the path. Did anything unexpected happen? If so, figure out what is going on.

Second, leaving aside your performance problem, I think you also have a correctness problem. Can you explain to us why you believe the Manhattan distance is a reasonable heuristic?

(For those reading this who are unfamiliar with the metric, the "Manhattan distance" or "taxi distance" is the distance between two points you'd have to travel if you lived in a city laid out on a grid. That is, to go 14 miles due northeast you'd have to travel 10 miles north and then 10 miles east for a total of 20 miles.)

The A* algorithm requires for its correctness that the heuristic always underestimates the actual distance required to travel between two points. If there are any "diagonal shortcut" streets in the graph then the Manhattan distance overestimates the distance on those paths and therefore the algorithm will not necessarily find the shortest path.

Why aren't you using the Euclidean distance as your heuristic?

Have you tried your algorithm using "always zero" as the heuristic? That is guaranteed to be an underestimate. (Doing so gives you an implementation of Dijkstra's Algorithm.)

Third, you seem to be doing an awful lot of sorting in this implementation. Surely you could be using a priority queue; that's a lot cheaper than sorting.

Fourth, I have an implementation of A* in C# 3 on my blog that you are welcome to use; no warranty expressed or implied, use at your own risk.

http://blogs.msdn.com/b/ericlippert/archive/tags/astar/

My code is very straightforward; the algorithm in my implementation looks like this:

var closed = new HashSet<Node>();
var queue = new PriorityQueue<double, Path<Node>>();
queue.Enqueue(0, new Path<Node>(start));
while (!queue.IsEmpty)
{
    var path = queue.Dequeue();
    if (closed.Contains(path.LastStep)) continue;
    if (path.LastStep.Equals(destination)) return path;
    closed.Add(path.LastStep);
    foreach(Node n in path.LastStep.Neighbours)
    {
        double d = distance(path.LastStep, n);
        var newPath = path.AddStep(n, d);
        queue.Enqueue(newPath.TotalCost + estimate(n), newPath);
    }
}

The idea is that we maintain a priority queue of paths; that is, a queue of paths that is always able to tell you the path so far with the least distance. Then we check to see if we've made it to our destination; if so, we're done. If not, then we enqueue a bunch of new paths based on their (under)estimated distance to the goal.

Fifth, that pseudocode in Wikipedia could be improved. The fact that my actual code is in many ways easier to follow than the pseudocode indicates that maybe there is too much detail in the pseudocode.

小苏打饼 2024-10-22 02:08:31

有几点需要注意:

List 并未针对删除第一个元素进行优化。更好的办法是按相反的顺序排序并取出最后一个元素。或者使用StackQueue

List.Remove(current) 效率极低。您已经知道要删除的索引,无需在整个列表中搜索该元素。

通过在正确位置插入新节点来保持 openNodes 排序应该比不断重新排列整个列表要快得多。跳过列表排序会删除重要的不变量,从而破坏整个算法。您需要加快排序速度,而不是跳过它。

您在 latedNodes 上执行的主要操作是存在测试,latedNodes.Contains()。使用为此优化的数据结构,例如Set。或者更好的是,在每个节点中放置一个关闭标志字段,并在每次传递开始时清除它们。这将比每次迭代中通过 closeNodes 进行线性搜索要快得多。

最初,您不应在 solutionNodes 中放置任何内容,mEndmStart 都将在遍历路径的最终循环期间添加。

neighborNodes 可以是 IEnumerable 而不是 List,因为您永远不需要一次完整的列表。使用 foreach 也比按索引枚举列表稍快。

A couple notes:

List<T> is not optimized for removing the first element. Better would be to sort in the opposite order and take the last element. Or use a Stack<T> or Queue<T>.

List.Remove(current) is extremely inefficient. You already know the index you want to remove, don't search the entire list for the element.

Keeping openNodes sorted by inserting new nodes in the correct location should be much faster than resorting the entire list continually. Skipping the list sort breaks the entire algorithm by removing important invariants. You need to make the sort faster, not skip it.

The primary operation you're doing on closedNodes is a presence test, closedNodes.Contains(). Use a data structure that is optimized for that, e.g. Set<T>. Or better yet, put a closed flag field in each node and clear them all at the beginning of each pass. This will be significantly faster than doing a linear search through closedNodes in each iteration.

You shouldn't put anything in solutionNodes initially, both mEnd and mStart will get added during the final loop that traverses the path.

neighborNodes could be an IEnumerable<T> instead of a List<T>, since you never need the entire list at once. Using foreach would also be slightly faster than enumerating the list by index.

猫瑾少女 2024-10-22 02:08:31

您可以将其与 quickgraph 库

QuickGraph.Algorithms.ShortestPath.AStarShortestPathAlgorithm<TVertex,TEdge>

You can compare it with (or just make use of) the A* implementation in quickgraph library:

QuickGraph.Algorithms.ShortestPath.AStarShortestPathAlgorithm<TVertex,TEdge>
心凉 2024-10-22 02:08:31

您可以这样计算遍历节点成本:

cost = current.G + 10;

然而对于启发式方法,您有一个简单的距离。为什么即使在这里也不使用相同的距离?根据您的节点当前的距离,您的启发式可能太低了。

另一个可能错误的“细节”:current.GetNeighborNodes。这是如何实施的?它是否返回相同位置的相同节点,以便共享不同路径上的相同节点,或者它是否总是使用 new 分配一个新节点?

You compute traversal node cost like this:

cost = current.G + 10;

Yet for heuristics you have a simple distance. Why not using the same distance even here? Depending on how far your nodes currently are, your heuristics may be a lot too low.

Another "detail" which might be wrong: current.GetNeighborNodes. How is this implemented? Does it return the same node as it should for the same location, so that the same node on different paths is shared, or does it always allocated a new node using new?

大海や 2024-10-22 02:08:31

内存消耗怎么样?下载红门工具。使用性能探查器来查看花费最多时间的地方,并使用内存探查器来确定是否存在内存泄漏或对象处理速度不够快的问题。

正如@Rodrigo 指出的,您可能需要处理一张大地图。嵌套循环永远不会具有高性能。

What is the memory consumption like? Download the Red Gate tools. Use Performance Profiler to see where the most time is being spent and Memory Profiler to determine if you have any issues with memory leaks or object not being disposed quickly enough.

As @Rodrigo pointed out, you could have a large map to deal with. Nested loops are never expected to be performant.

疾风者 2024-10-22 02:08:31

您是否使用网格来表示地形?如果是这样,那么在这种情况下最好的启发式是八分位数:

启发式成本= (min(x 的差异,y 的差异) * 2 的平方根 + max(x 的差异,y 的差异) - min(x 的差异, y))

对于网格来说,这始终是最佳的。不幸的是,这种启发式方法并不为人所知。

另一个有用的提示是为打开列表选择适合地图大小的数据结构。如果您的地图相对较小(100 x 100),那么未排序的向量将是最快的方法。要删除元素,只需将最后一个元素与要删除的元素进行迭代器交换并调用 pop_back 即可。如果您有更大的地图,请使用堆。您只关心最便宜的节点,因此对其他所有节点进行排序不会有任何好处。堆插入和排序的复杂度为 log n,非常适合中型和大型数据集,但对于小型数据集来说速度很慢。

最后,如果速度是一个很大的问题,请实施跳跃点搜索。平均而言,它比寻路 A* 快 20 到 30 倍,并且没有内存开销(研究论文声称,尚未找到任何相关证据)。它基本上会用“查找后继者”代替 A* 的“查找邻居”步骤,因此将其合并到您的代码中应该相对简单。

希望有帮助。

Are you using a grid for your terrain representation ? If so, then the best heuristic in that case is Octile:

Heuristic Cost= (min(Differrence in x, Differrence in y) * square root of 2 + max(Differrence in x, Differrence in y) - min(Differrence in x, Differrence in y))

For grids, this will always be optimal. Unfortunate this heuristic isn't so well known.

Another useful tip is to choose a data structure for your open list to suit the size of your map. If your map is relatively small (100 x 100), then an unsorted vector will be the fastest way to go. To remove elements, simply do an iterator swap of the last element and the one you want to remove and call pop_back. If you have a bigger map, use a heap. You only care about the cheapest node, so sorting everything else will have no benefit. A heap inserts and sorts with complexity log n, perfect for medium and large data sets but slow for small ones.

Lastly, if speed is so great an issue, implemente Jump Point Search. It is, on average, 20 to 30 times faster than pathfinding A*, with no memory overhead (or so the research paper claims, haven't found any proof about that one). It will basically substitute the "find neighbors" step of A* with "find successors", so incorporating it into your code should be relatively simple.

Hope that helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文