C语言实现Dijkstra算法(邻接矩阵与邻接表存储方式)
-
代码 #include <stdio.h>
#include <stdlib.h>
typedef int ArcType;
typedef char VerTextType[20];
#define MVNum 100
#define INF 0x3f3f3f3f
typedef struct
{
VerTextType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum;
int arcnum;
} AMGraph;
typedef struct ArcNode
{
int adjver;
struct ArcNode *nextarc;
ArcType weight;
} ArcNode;
typedef struct VNode
{
VerTextType data;
ArcNode *firstarc;
} VNode, AdjList[MVNum];
typedef struct node
{
AdjList vertices;
int vexnum;
int arcnum;
} ALGraph;
void ShortestPath_DIJ1(AMGraph G, int v0, ArcType D[], int Path[])
{
int ok[MVNum], i, j;
for(i = 0; i < G.vexnum; i++) {
ok[i] = 0;
Path[i] = -1;
D[i] = INF;
}
D[v0] = 0;
for(i = 0; i < G.vexnum; i++) {
int min_node = -1;
for(j = 0; j < G.vexnum; j++) {
if(ok[j] == 0 && (min_node == -1 || D[j] < D[min_node])) {
min_node = j;
}
}
if(min_node == -1) break;
ok[min_node] = 1;
for(j = 0; j < G.vexnum; j++) {
if(ok[j] == 0 && G.arcs[min_node][j] != 0 && D[j] > D[min_node] + G.arcs[min_node][j]){
D[j] = D[min_node] + G.arcs[min_node][j];
Path[j] = min_node;
}
}
}
}
void ShortestPath_DIJ2(ALGraph G, int v0, ArcType D[], int Path[])
{
int ok[MVNum], i, j;
for(i = 0; i < G.vexnum; i++) {
ok[i] = 0;
Path[i] = -1;
D[i] = INF;
}
D[v0] = 0;
for(i = 0; i < G.vexnum; i++) {
int min_node = -1;
for(j = 0; j < G.vexnum; j++) {
if(ok[j] == 0 && (min_node == -1 || D[j] < D[min_node])) {
min_node = j;
}
}
if(min_node == -1) break;
ok[min_node] = 1;
ArcNode * cur = G.vertices[min_node].firstarc;
while(cur != NULL) {
if(ok[cur -> adjver] == 0 && D[cur -> adjver] > D[min_node] + cur -> weight) {
D[cur -> adjver] = D[min_node] + cur -> weight;
Path[cur -> adjver] = min_node;
}
cur = cur -> nextarc;
}
}
}
void init_graph(AMGraph *g1, ALGraph *g2) {
int n,m;
scanf("%d %d",&n,&m);
g1-> vexnum = g2-> vexnum = n;
g1-> arcnum = g2-> arcnum = m;
for(int i=0;i<MVNum;i++) for(int j=0;j<MVNum;j++) g1-> arcs[i][j]=0;
for(int i=0;i<MVNum;i++) g2-> vertices[i].firstarc = NULL;
for(int i=1;i<=m;i++) {
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
g1-> arcs[u][v] = w;
ArcNode *cur = g2-> vertices[u].firstarc;
if(cur == NULL) {
g2-> vertices[u].firstarc = (ArcNode *) malloc(sizeof(ArcNode));
g2-> vertices[u].firstarc -> adjver = v;
g2-> vertices[u].firstarc -> weight = w;
g2-> vertices[u].firstarc -> nextarc = NULL;
}else{
while(cur ->nextarc != NULL) {
cur = cur -> nextarc;
}
cur -> nextarc = (ArcNode *) malloc(sizeof(ArcNode));
cur = cur -> nextarc;
cur -> adjver = v;
cur -> weight = w;
cur -> nextarc = NULL;
}
}
}
int main() {
AMGraph g1;
ALGraph g2;
init_graph(&g1,&g2);
int d1[MVNum],d2[MVNum],path1[MVNum],path2[MVNum];
ShortestPath_DIJ1(g1,0,d1,path1);
for(int i =0;i<g1.vexnum;i++) printf("%d ",path1[i]);
printf("\n");
ShortestPath_DIJ2(g2,0,d2,path2);
for(int i =0;i<g2.vexnum;i++) printf("%d ",path2[i]);
printf("\n");
}
|