迪杰斯特拉算法
代码如下:
#include <iostream> using namespace std; typedef struct Node { int shortdist; //用于记录到节点的最短距离 int flag; //用作标志变量,表示借点已经加入到集合中 int prev; //节点的前驱结点 } Node; void Dijkstra(int num,int startvertex,int map[][10],Node *vertex) { for(int i=0;i<num;i++) { vertex[i].shortdist=map[startvertex][i]; if(i==startvertex) vertex[i].flag=true; //将节点加入结合 else vertex[i].flag=false; //标记其余节点未被加入结合 if(vertex[i].shortdist<100) vertex[i].prev=startvertex; //标记节点前驱 else vertex[i].prev=-1; } for(int i=0;i<num-1;i++) { int temp=100; int findmin=-1; for(int j=0;j<num;j++) //发现与当前起始节点关联的距离最短的节点 if(vertex[j].flag==false&&vertex[j].shortdist<temp) { temp=vertex[j].shortdist; findmin=j; } if(findmin!=-1) vertex[findmin].flag=true; //将该距离最短节点加入到集合 for(int j=0;j<num;j++) //利用新加入的节点更新最短距离 if(vertex[j].flag==false&&(vertex[findmin].shortdist+map[findmin][j]<vertex[j].shortdist)) { vertex[j].shortdist=vertex[findmin].shortdist+map[findmin][j]; vertex[j].prev=findmin; } } cout<<"Result: "<<endl<<"Source:"<<startvertex+1<<endl; for(int i=0;i<num;i++) if(vertex[i].flag==true) { cout<<i+1<<" distance:"<<vertex[i].shortdist<<" path:"; int prev=i; if(prev==startvertex) cout<<prev+1; while(prev!=startvertex) { cout<<vertex[prev].prev+1<<" "; prev=vertex[prev].prev; } cout<<endl; } else cout<<i+1<<" Can't reach!"<<endl; //cout<<endl; } int main() { int map[10][10],row,col; cin>>row>>col; if(row!=col) { cout<<"Wrong!"<<endl; return 0; } int num=row; Node *vertex=new Node[col]; for(int i=0;i<num;i++) for(int j=0;j<num;j++) cin>>map[i][j]; //节点间距离为0-99,100表示无穷远 for(int startvertex=0;startvertex<num;startvertex++) Dijkstra(num,startvertex,map,vertex); }
结果: