Dijkstra(從一個源點到其他各點的最短路徑)
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct
{
int vertex[MAXSIZE];
int edges[MAXSIZE][MAXSIZE];
}Graph;
void creatGraph(Graph *p)
{
int n,e,i,j,k,x;
printf(“print the number of vertex\n”);
scanf("%d",&n);
// printf(“input data of vertex\n”);
for(i=0;i<n;i++)//初始化頂點資訊
{
//scanf("%d",&j);
//p->vertex[i]=j;
p->vertex[i]=i;
}
for(i=0;i<n;i++)//初始化邊關係
for(j=0;j<n;j++)
p->edges[i][j]=9;//設9為極大值
printf("print the number of edges\n");
scanf("%d",&e);
for(k=0;k<e;k++)
{
printf("input edge of(i,j)\n");
scanf("%d%d",&i,&j);
printf("input the value of it\n");
scanf("%d",&x);
p->edges[i][j]=x;
p->edges[j][i]=x;
}
}
void showGraph(Graph *p,int n)
{
int i,j;
printf(“vertex\n”);
for(i=0;i<n;i++)
printf("%4d",p->vertex[i]);
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%4d",p->edges[i][j]);
}
printf("\n");
}
void Dijkstra(int gm[][MAXSIZE],int v0,int n)
{
int dist[MAXSIZE],path[MAXSIZE],s[MAXSIZE];
//dist 表示當前vo到vi的最短路徑。
int i,j,k,mindis;
for(i=0;i<n;i++)//初始化,將與vo有關邊的權值賦給dist
{
dist[i]=gm[v0][i];
s[i]=0;
if(gm[v0][i]<9)
path[i]=v0;//表示從v0到vi最短路徑當前的節點為vo
else
path[i]=-1;
} s[v0]=1;path[v0]=0;//v0的最短路徑已知,前驅亦已知 for(i=0;i<n;i++) { mindis=9; for(j=0;j<n;j++) if(s[j]==0&&dist[j]<mindis) { k=j; mindis=dist[j]; } s[k]=1; for(j=0;j<n;j++) if(s[j]==0) if(gm[k][j]<9&&dist[k]+gm[k][j]<dist[j]) { dist[j]=dist[k]+gm[k][j]; path[j]=k; } }
}
int main()
{
Graph M,*p=&M;
creatGraph§;
showGraph(p,6);
return 0;
}