最短路徑(迪傑斯特拉算法)
阿新 • • 發佈:2018-12-08
ace info urn itl int -- iostream pro src
求上圖中從V1 到V10的最短路徑
程序輸入說明
輸入圖的鄰接矩陣表示程序輸出說明
輸出路徑序列程序輸入樣例
0 2 5 1 -1 -1 -1 -1 -1 -1 -1 0 -1 -1 12 14 -1 -1 -1 -1 -1 -1 0 -1 6 10 4 -1 -1 -1 -1 -1 -1 0 13 12 11 -1 -1 -1 -1 -1 -1 -1 0 -1 -1 3 9 -1 -1 -1 -1 -1 -1 0 -1 6 5 -1 -1 -1 -1 -1 -1 -1 0 -1 10 -1 -1 -1 -1 -1 -1 -1 -1 0 -1 5 -1 -1 -1 -1 -1 -1 -1 -1 0 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 0
程序輸出樣例
1 3 5 8 10
1 #include<iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 using namespace std; 6 7 bool vis[15]; 8 int map[15][15], d[15], p[15]; 9 const int INF = 999999; 10 11 int main() 12 { 13 for(int i = 0; i < 10; i++) {14 for(int j = 0; j < 10; j++) { 15 cin>>map[i][j]; 16 if(map[i][j] == -1) 17 map[i][j] = INF; 18 } 19 } 20 memset(vis, 0, sizeof(vis)); 21 for(int i = 0; i < 10; i++) 22 d[i] = INF; 23 d[0] = 0; 24 for(int i = 0; i < 10; i++) { 25 int cur, min = INF; 26 for(int k = 0; k < 10; k++) { 27 if(d[k] <= min && !vis[k]) { 28 min = d[k]; 29 cur = k; 30 } 31 } 32 vis[cur] = true; 33 for(int k = 0; k < 10; k++) { 34 if(d[k] > d[cur] + map[cur][k]) { 35 d[k] = d[cur] + map[cur][k]; 36 p[k] = cur; 37 } 38 } 39 } 40 int dir[15]; 41 int x = 9, c = 0; 42 while(x != p[x]) { 43 dir[c++] = x; 44 x = p[x]; 45 } 46 dir[c] = 0; 47 for(int i = c; i > 0; i--) 48 cout<<dir[i]+1<<" "; 49 cout<<dir[0]+1<<endl; 50 return 0; 51 }
最短路徑(迪傑斯特拉算法)