#include<iostream>
#define maxint 1<<30
#define Max 10
using namespace std;
void print(int* dist){
for(int i = 1; i <= 5; i++){
cout<<dist[i]<<" ";
}
cout<<endl;
}
void Dijkstra(int c[][6], int n, int v, int* dist, int* prev)
{ // 单源最短路径问题的Dijkstra算法
bool s[Max];
for(int i=1; i<=n; i++){
dist[i] = c[v][i]; // v到其余各点vi的当前最短路径长度的初值
s[i] = false;
if(dist[i] == maxint) prev[i] = 0; // <v, vi>?V
else prev[i] = v; // 到点i最短路径的上一个点为源点(初值)
}
dist[v] = 0; s[v] = true; // s中包含源点v
for(int i=1; i<n; i++){
int temp = maxint;
int u;
for(int j=1; j<=n; j++) // 在S中并入下一条具有最短路径长度的终点j
if((!s[j]) && (dist[j]<temp)) {u = j; temp = dist[j];}
s[u] = true;
for(int j=1; j<=n; j++){ // 修改从v到V-S中任一顶点的最短路径长度
if((!s[j]) && (c[u][j]<maxint)){
int newdist = dist[u] + c[u][j];
if(newdist<dist[j]) {dist[j] = newdist; prev[j] = u;}
}
}
}
}
int main(){
int c[6][6];
for(int i = 1; i <= 5; i++){
for(int j = 1; j <= 5; j++){
c[i][j] = maxint;
}
}
c[1][2] = 10; c[1][4] = 30; c[1][5] = 100; c[2][3] = 50; c[3][5] = 10; c[4][3] = 20; c[4][5] = 60;
int dist[6], prev[6];
Dijkstra(c, 5, 1, dist, prev);
print(dist);
system("pause");
return 0;
}
Dijkstra
最新推荐文章于 2023-02-22 23:33:21 发布