簡體   English   中英

如何加快我的A *尋路功能?

[英]How can I speed up my A* Pathfinding?

當沒有障礙物移動或從障礙物的頂部移動到障礙物的側面時,我的尋路效果很好,但是當它需要找到從障礙物的頂部到底部的路徑時,速度太慢。

我相當確定這是我對每個循環進行排序或通過封閉集進行循環的方式,但是我不確定如何避免這種情況,因為Windows Phone 7上沒有SortedLists

//This Vivid Destination means it doesn't have to find the exact location 
//which is helpful as it is continuous environment  
Rectangle vividDestination = new Rectangle((int)character.destination.X - 10, (int)character.destination.Y - 10, 20, 20);

while (!vividDestination.Contains(Maths.vectorToPoint(OpenNodes[0].position)))
{
    Node Current = OpenNodes[0];
    OpenNodes.RemoveAt(0);
    ClosedNodes.Add(Current);
    Current.calculateNeightbours();

    foreach (Node neighbour in Current.neighbours)
    {
        neighbour.parents = Current.parents + 1;
        //The cost of the node is the amount of parent nodes + the distance to destination
        neighbour.cost = calculateCost(neighbour.position, character.destination, neighbour.parents);

        for (int i = 0; i < OpenNodes.Count; i++)
        {
            //Round Vector rounds the floats in the Vector to the nearest integer
            if (Maths.roundVector(OpenNodes[i].position) == Maths.roundVector(neighbour.position) && OpenNodes[i].parents < neighbour.parents)
            {
                break;
            }
            else
            {
                OpenNodes.RemoveAt(i);
                OpenNodes.Add(neighbour);
                i--;
                break;
            }
        }

        bool closedNode = false;
        for (int i = 0; i < ClosedNodes.Count; i++)
        {
            if (Maths.roundVector(ClosedNodes[i].position) == Maths.roundVector(neighbour.position))
            {
                closedNode = true;
                break;
            }
        }

        if (!closedNode)
        {
            OpenNodes.Add(neighbour);
        }
    }

    OpenNodes = OpenNodes.OrderBy(item => item.cost).ToList();
}

您正在做的事情效率低下。 列表的排序花費n * log(n)的時間,並且您對圖形中的每個頂點都對列表進行了一次排序。 這導致算法花費V ^ 2 * log(V)時間,其中V是頂點數。 如果僅保留未排序的列表,則可以通過遍歷所有項目並保持到目前為止的最低計數來提取線性時間中的最小值。 在這種情況下,時間變為V ^ 2。 這只是微小的改進。 當然,如果您使用適當的優先級隊列(例如基於Binary Heap的隊列),則該算法將運行得多,更快得多,因為這樣操作僅花費log(n)。 編寫自己的二進制堆不是很困難,如果平台本機不支持,我強烈建議您這樣做。 在這種情況下,插入和找到最小值僅花費log(n)時間,從而導致E log V時間(其中E是邊的數量,在平面圖中與V成正比)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM