最短路徑問題(dijkstra演算法)
阿新 • • 發佈:2018-12-12
11 0 11 27 11 12 29 26 42 22 36 34 11 0 18 3 4 19 16 32 13 28 25 27 18 0 18 16 9 6 17 15 11 13 11 3 18 0 3 19 16 32 15 27 25 12 4 16 3 0 17 15 31 14 26 24 29 19 9 19 17 0 7 17 20 11 17 26 16 6 16 15 7 0 17 14 14 12 42 32 17 32 31 17 17 0 25 13 11 22 13 15 15 14 20 14 25 0 26 15 36 28 11 27 26 11 14 13 26 0 18 34 25 13 25 24 17 12 11 15 18 0
直接給出問題的輸入,第一行表示有多少個節點,接下來n行表示n個節點之間的距離,現要找出 從 某一 節點 到 其他節點的最短路徑,兩兩節點可以都可以到達,但是每從 一個節點 到 另一個節點 時所經過的路程不能超過15。
我的程式碼:
#include <iostream> #include <cstring> #include <iomanip> #define INF 0x3f3f3f3f using namespace std; const int maxn = 1<<10; // 最大 2 的十次方 int n,map[maxn][maxn],way[maxn]; //n為節點個數 void djs(int start) { int dis[n+1], vis[n+1] = {0}; memset(dis, 0x3f, sizeof(dis)); dis[start] = 0; //自己到自己的距離為 0************** for(int i = 1; i <= n; i++) { //迴圈n次 == 迭代n次 int flag = -1; for(int j = 1; j <= n; j++) //找到到 未訪問的 start 最短的點 if(vis[j] == 0) { if(flag == -1) { flag = j; continue; } else if(dis[j] < dis[flag]) flag = j; } vis[flag] = 1; for(int j = 1; j <= n; j ++) //更新dis if(dis[j] > dis[flag] + map[flag][j] && map[flag][j] <= 15) dis[j] = dis[flag] + map[flag][j],way[j] = flag; //記錄到達某點最短距離的上一個節點 } for(int i = 1; i <= n; i++) cout <<setw(3) << setiosflags(ios::left) << dis[i] << " "; cout <<endl; } void find(int start,int end) { int road[n], last = end; int flag=0; djs(start); while(1) { //返回去找 road[flag]=way[end]; end=way[end]; flag++; if(end==start) break; } for(int i = flag - 1; i >= 0; i--)cout << road[i] << "=>"; cout << last; } int main() { memset(map, 0x3f, sizeof(map)); cin >> n; //初始化地圖無窮大 int temp; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> temp, map[i][j] = map[j][i] = temp; for(int i = 1; i <= n; i++) cout << setw(5) << setiosflags(ios::left) << i ; cout <<endl; for(int i = 1; i <= n; i++) djs(i); cout << "你想知道從哪到哪的路徑?"; //突然想知道最短路徑是怎麼走的,所以強行加上 int a, b; cin >> a >> b; find(a, b); return 0; } /* dijkstra 11 0 11 27 11 12 29 26 42 22 36 34 11 0 18 3 4 19 16 32 13 28 25 27 18 0 18 16 9 6 17 15 11 13 11 3 18 0 3 19 16 32 15 27 25 12 4 16 3 0 17 15 31 14 26 24 29 19 9 19 17 0 7 17 20 11 17 26 16 6 16 15 7 0 17 14 14 12 42 32 17 32 31 17 17 0 25 13 11 22 13 15 15 14 20 14 25 0 26 15 36 28 11 27 26 11 14 13 26 0 18 34 25 13 25 24 17 12 11 15 18 0 */