优化路径查找代码

时间:2013-04-22 17:32:13

标签: c# linq iteration

首先是一小部分背景。我正在开发一个在位置之间生成“路线”的系统。位置具有预定义的邻居列表,不限于与其相邻的邻居。搜索可以安全地假设通过选择最接近的邻居(数字地)到目标目的地,它正在朝向它进行最佳移动。

我的工作代码如下所示:

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和order的使用,但也评论说这种方法可能效率低下。我需要效率而不是整洁。

非常感谢。

0 个答案:

没有答案