0

先说一点背景。我正在开发一个在位置之间生成“路线”的系统。位置具有预定义的邻居列表,不限于与其相邻的邻居。搜索可以安全地假设,通过选择离目标目的地最近的邻居(数字上),它正在朝着它做出最佳移动。

我有如下所示的工作代码:

public Route GetRoute(int StartPoint, int Destination)
{
    Route returnRoute = new Route();
    returnRoute.steps = new List<int>();
    bool locationReached = false;
    int selectedNeighbour;
    int distanceFromTarget;
    int currentPoint = StartPoint; // set the current point to the start point

    while (!locationReached)
    {
        selectedNeighbour = 0;
        distanceFromTarget = 5000; // nominal amount guaranteed to be overwritten

        var neighbours = locations.FirstOrDefault(l => l.LocationID == currentPoint).Neighbours;

        for (int i = 0; i < neighbours.Length; i++)
        {
            // get the current neighbours, then check proximity
            int currentNeighbour = neighbours[i];
            int tempDistance = Math.Abs( currentNeighbour - Destination );

            // if nearer than previous neighbour, set it as the chosen location
            if ( tempDistance < distanceFromTarget )
            {
                distanceFromTarget = tempDistance;
                selectedNeighbour = currentNeighbour;

                // if the selected neighbour is the destination, we're done
                if ( selectedNeighbour == Destination )
                    locationReached = true;
            }

        } // for

        // add the selected neighbour if we found one
        if ( selectedNeighbour != 0 )
        {
            currentPoint = selectedNeighbour;
            returnRoute.steps.Add(selectedNeighbour);
        }
        else 
        {
            Debug.Log ("No Route Found");
            return returnRoute; 
        }

    } // while

    return returnRoute;
}

我的问题是关于邻居 (int[]) 变量的循环。如何最好地优化它?我见过一些使用 linq 和 ordering 的方法,但也评论说这种方法可能效率低下。我在这里需要效率而不是整洁。

非常感谢。

4

0 回答 0