使用Windows窗体在世界地图上实现Djikstra算法

时间:2017-05-14 09:26:50

标签: c# algorithm

我正在制作一个项目,我有一张世界地图,我在其上标记了几个点,每个点代表一个国家。我想实现Djiktra的算法来找到从源国到目的地县的最短路径。我在网上搜索了c#中的算法,我发现了一个常见的解决方案:

    private static int MinimumDistance(int[] distance, bool[] shortestPathTreeSet, int verticesCount)
{
    int min = int.MaxValue;
    int minIndex = 0;

    for (int v = 0; v < verticesCount; ++v)
    {
        if (shortestPathTreeSet[v] == false && distance[v] <= min)
        {
            min = distance[v];
            minIndex = v;
        }
    }

    return minIndex;
}

private static void Print(int[] distance, int verticesCount)
{
    Console.WriteLine("Vertex    Distance from source");

    for (int i = 0; i < verticesCount; ++i)
        Console.WriteLine("{0}\t  {1}", i, distance[i]);
}

public static void Dijkstra(int[,] graph, int source, int verticesCount)
{
    int[] distance = new int[verticesCount];
    bool[] shortestPathTreeSet = new bool[verticesCount];

    for (int i = 0; i < verticesCount; ++i)
    {
        distance[i] = int.MaxValue;
        shortestPathTreeSet[i] = false;
    }

    distance[source] = 0;

    for (int count = 0; count < verticesCount - 1; ++count)
    {
        int u = MinimumDistance(distance, shortestPathTreeSet, verticesCount);
        shortestPathTreeSet[u] = true;

        for (int v = 0; v < verticesCount; ++v)
            if (!shortestPathTreeSet[v] && Convert.ToBoolean(graph[u, v]) && distance[u] != int.MaxValue && distance[u] + graph[u, v] < distance[v])
                distance[v] = distance[u] + graph[u, v];
    }

    Print(distance, verticesCount);
}

主要课程如下:

  int[,] graph = {
    { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
    { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
    { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
    { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
    { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
    { 0, 0, 4, 0, 10, 0, 2, 0, 0 },
    { 0, 0, 0, 14, 0, 2, 0, 1, 6 },
    { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
    { 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};

Dijkstra(graph, 0, 9);

我的问题是:我案例中的图表是什么?我应该在我的主要部分调用Djikstra函数的参数是什么? 谢谢你的帮助!!

0 个答案:

没有答案