我试图在C中实现Dijkstra算法,我理解算法并知道它是如何工作的,但我不知道如何抓住它所做的路径。有人有线索吗?
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define INF 1000
#define NUM_OF_NODES 4
#define MEMBER 1
#define NOMEMBER 0
void dijkstra(int weight[][NUM_OF_NODES],int s,int t,int *pd, int precede[])
{
int distance[NUM_OF_NODES],perm[NUM_OF_NODES],prev[NUM_OF_NODES];
int current,i,j,k,dc;
int smalldist,newdist;
for (int i = 0; i < NUM_OF_NODES; i++)
{
perm[i] = NOMEMBER;
distance[i] = INF;
prev[i] = -1;
}
perm[s] = MEMBER;
distance[s] = 0;
current = s;
while(current != t)
{
smalldist = INF;
dc = distance[current];
for (int i = 0; i < NUM_OF_NODES; i++)
{
if (perm[i] == NOMEMBER)
{
newdist = dc + weight[current][i];
if (newdist < distance[i])
{
distance[i] = newdist; // Count the updated distance
precede[i] = current;
}
if (distance[i] < smalldist)
{
smalldist = distance[i];
k = i;
}
}
}//end of for and if
current = k;
perm[current] = MEMBER;
}//end while
*pd = distance[t];
} //end of function
我想从程序输出的输出是0 - &gt; 3:13或类似的东西......
答案 0 :(得分:2)
据我所知,你有前面的节点数组。
在这种情况下,输出路径应该像通过
那样简单void print_path(int s, int t, int precede[]) {
int current = t;
while (current != s) {
printf("%d -> ", current);
current = precede[current];
}
printf("%d\n",current);
}
打印从t
到s
的最短路径。
修改强>
运行方式:
int precede[NUM_OF_NODES];
dijkstra(weight,s,t,pd, precede);
print_path(s,t,precede); // will print shortest a path from t to s