Dijkstra:
单源到多源的最短路径算法
维护一个dist数组,每次在dist数组中寻找一个最短的且未访问的顶点,去更新其他剩下的顶点,直到所有的顶点都访问完毕。
源码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<climits>
using namespace std;
const int N=100;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
------------------- Dijkstra -----------------------------
从点A到其它所有点的最短路径
*/
int map[N][N]; //邻接矩阵表示图
bool boo[N];
int dis[N];
int a,b;
int c=0;
int foot[N];
int key1,key2,value;
void dijkstra(int key){
foot[c++]=key;
boo[key]=1;
dis[key]=0;
int tag=key;
for(int i=0;i<a-1;++i){ //仅仅是枚举次数
//更新dis
for(int k1=0;k1<a;k1++){
if(map[tag][k1]!=0 && map[tag][k1]!=INT_MAX && boo[k1]==0 ){ //当前k1需要更新
cout<<"dis[k1]:"<<dis[k1]<<endl;
cout<<"dis[tag]:"<<dis[tag]<<endl;
//1. 当 dis=无穷
//2. 当有值 外来的比原来的小
if(dis[k1]==INT_MAX|| dis[tag]+map[tag][k1]<dis[k1]){
dis[k1]=dis[tag]+map[tag][k1];
}
}
}
//打印dis
cout<<"dis:"<<endl;
for(int k=0;k<a;k++){
cout<<dis[k]<<" ";
}
cout<<endl;
//找最小的路径
cout<<"next:"<<endl;
int next=INT_MAX;
for(int j=0;j<a;j++){
if(boo[j]!=1 && dis[j]!=0 && dis[j]<next){
next=dis[j];
tag=j;
}
}
cout<<"tag:"<<tag<<endl;
boo[tag]=1;
foot[c++]=tag;
}
//打印路径
cout<<endl;
cout<<"foot:"<<endl;
for(int i=0;i<a;i++){
cout<<foot[i]<<"-";
}
//打印数值
cout<<"dis:"<<endl;
for(int i=0;i<a;i++){
cout<<dis[i]<<"-";
}
}
int main(int argc, char *argv[]) {
int G[6][4];
fill(G[0],G[0]+6*4,520);
for(int i=0;i<6;i++){
for(int j=0;j<4;j++){
cout<<G[i][j]<<" ";
}
cout<<endl;
}
cout<<"请输入顶点数和边数:例如 5 6"<<endl;
cin>>a>>b;
fill(map[0],map[0]+N*N,INT_MAX);
fill(dis,dis+a,INT_MAX);
for(int i=0;i<b;i++){
cin>>key1>>key2>>value;
map[key1][key2]=value;
map[key2][key1]=value;
}
for(int i=0;i<b;i++){
for(int j=0;j<b;j++){
if(i==j){
map[i][j]=0;
break;
}
}
}
cout<<"show map:"<<endl;
for(int i=0;i<b;i++){
for(int j=0;j<b;j++){
cout<<map[i][j]<<" ";
}
cout<<endl;
}
dijkstra(0);
return 0;
}