【问题标题】:Printing the path in dijstra's algorithm在 dijkstra 算法中打印路径
【发布时间】:2015-04-05 04:26:06
【问题描述】:

我的cs教授给了我一个dijstras算法的实现,他要求我们修改它以打印从源节点“src”(见代码)到每个节点的路径,以及距离(它已经做)。我已经看了大约一个星期了,并尝试了几件事。我无法为我的一生弄清楚...任何帮助将不胜感激。该图由一个邻接矩阵表示,并且有一个包含其大小的全局:

int n; //Global matrix's size
int minDistance(int dist[], bool sptSet[]){
    // Initialize min value
    int min = INT_MAX, min_index;
    int i = 0;
    for ( i = 0; i < n; i++)
        if (sptSet[i] == false && dist[i] <= min)
            min = dist[i], min_index = i; 
   return min_index;
}

int printSolution(int dist[]){
   printf("Vertex   Distance from Source\n");
   int i;
   for (i = 0; i < n; i++)
      printf("%d \t\t %d\n", i, dist[i]);
}

void dijkstra(int ** graph, int src){
    //correting zeros (won't work with negative values)
    correctZeros(graph);
    int dist[n]; 
    bool sptSet[n];
    int i;
    for (i = 0; i < n; i++)
        dist[i] = INT_MAX, sptSet[i] = false;
    dist[src] = 0;

    // Find shortest path for all vertices
    int count;
    for (count = 0; count < n; count++){
        int u = minDistance(dist, sptSet);
        sptSet[u] = true;
        int j;
        for (j = 0; j < n; j++){
            printf("%d", u);
            if (!sptSet[j] && graph[u][j] && dist[u] != INT_MAX && dist[u]+graph[u][j] < dist[j]){
                dist[j] = dist[u] + graph[u][j];

            }
        }
    }
    printSolution(dist);
}

【问题讨论】:

    标签: c dijkstra shortest-path


    【解决方案1】:

    您需要做的就是为每个节点存储最短路径的下一跳是什么。每当您更新节点最短路径的距离时,此信息都会更新。

    【讨论】:

      【解决方案2】:

      在进行松弛计算时,使用另一个数组来存储前一个节点。

      node[src] = src; //init source node
      if (!sptSet[j] && graph[u][j] && dist[u] != INT_MAX && dist[u]+graph[u][j] < dist[j]){
                  dist[j] = dist[u] + graph[u][j];
                  node[j] = u; //store previous node step
              }
      

      使用循环打印所有节点,直到 node[x] = x(源节点)

      printPath(int node[], int i, int src)
      {
      
          int currentNode = i;
          printf(currentNode); 
          while(currentNode!=src)
          {
               printf(node[currentNode]);
               currentNode = node[currentNode];
          }
      }
      

      我对C语言不是很熟悉,所以可能有一些C语法错误。谢谢。

      【讨论】:

        猜你喜欢
        • 2020-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多