Dijkstra算法
void printPath(int path, int a){
int stack[maxSize],top= -1;
while(path[a]!=-1){
stack[++top] = a;
a = path[a];
}
stack[++top]=a;
while(top!=-1)
print(stack[++top]+" ");
print("\n");
}
void Dijkstra(MGraph g, int v, int dist[], int path[]){
int set[maxSize];
int min, i, j;
for(i = 1;i <= g.n; i++){
dist[i] = g.edges[v][i];
set[i] = 0;
if(g.edges[v][i] < INF)
path[i] = v;
else
path[i] = -1;
}
set[v] = 1;
path[v] = -1;
for(i = 1; i <= g.n; ++i){
min = INF;
for(j = 1; j <= g.n; ++j){
if(set[j]==0&&dist[j] < min){
min = dist[j];
u = j;
}
}
for(j = 1; j <=g.n; ++j){
if(set[j]==0&& dist[j] > dist[u]+g.edges[u][j]){
dist[j] = dist[u]+g.edges[u][j];
path[j] = u;
}
}
}
}
Floyd算法:
void Floyd(MGraph g, int A[][maxSize], int path[][maxSize]){
int i, j, k;
for(i = 0;i < g.n; ++i){
A[i][j] = g.edges[i][j];
path[i][j] = -1;
}
for(k = 0; k < g.n; ++k){
for(i = 0; i < g.n; ++i){
for(j = 0; j < g.n; ++j){
if(A[i][j]> A[i][k]+A[k][j]){
A[i][j] = A[i][k]+A[k][j];
Path[i][j] = k;
}
}
}
}
}