引用一个GIF说明这个算法:
图片来源: poj 2387 Dijkstra入门(动态图解)_迪杰斯特拉动图gif_「已注销」的博客-CSDN博客
算法总的来讲,并不难,图解很清晰
首先处理一下图,得到邻接矩阵:
0 | 7 | 9 | N | N | 14 |
7 | 0 | 10 | 15 | N | N |
9 | 10 | 0 | 11 | N | 2 |
N | 15 | 11 | 0 | 6 | N |
N | N | N | 6 | 0 | 9 |
14 | N | 2 | N | 9 | 0 |
N:表示暂时不可达
实现(C):
#include<stdio.h>
#define N 999
#define maxsize 999
struct set{
int num;
int point[maxsize];
};
int n;
struct set s;
void init(){
s.num = 1;
s.point[0]=0;
}
bool isfull(){
if(s.num==n)
return true;
else return false;
}
bool isinS(int k){
for(int i=0;i < s.num;i++){
if(s.point[i] == k)
return true;
}
return false;
}
void dijstra(int a[6][6], int res[]){
while (!isfull()){
int min=N,temp=0;
for(int i=1;i < n;i++){
if(!isinS(i) and res[i]<min){
min = res[i];
temp = i;
}
}
s.point[s.num] = temp;
s.num+=1;
for(int i=1;i < n;i++){
if(!isinS(i) and a[temp][i]+res[temp] < res[i]){
res[i] = a[temp][i]+res[temp];
}
}
}
}
int main(){
int arr[6][6] = { {0,7,9,999,999,14},
{7,0,10,15,999,999},
{9,10,0,11,999,2},
{999,15,11,0,6,999},
{999,999,999,6,0,9},
{14,999,2,999,9,0}};
int res[] = {0,7,9,999,999,14};
init();
n = 6;
dijstra(arr,res);
for (int i=1;i < n;i++){
printf("结点 1 到结点 %d 的最短距离:%d \n",i,res[i]);
}
return 0;
}