單源最短路徑dijkstral演算法
阿新 • • 發佈:2022-04-05
手寫迪傑斯特拉-Dijkstra
轉自:https://www.bilibili.com/video/BV1jE411W7tT?share_source=copy_web
輸入檔案:(test.txt)
7
0 5 2 9999 9999 9999 9999
5 0 9999 1 6 9999 9999
2 9999 0 6 9999 8 9999
9999 1 6 0 1 2 9999
9999 6 9999 1 0 9999 7
9999 9999 8 2 9999 0 3
9999 9999 9999 9999 7 3 0
採用floyed演算法計算計算出來的結果:
1 #include <iostream> 2#include <vector> 3 4 using namespace std; 5 6 constexpr int INF = 0x3F; 7 8 vector<int> dijkstral(const vector<vector<int>> &graph, int start) { 9 int n = graph.size(); 10 vector<int> dis(n, INF); // 初始化起點到各節點最短距離為無窮大 11 vector<bool> visited(n, false); // 初始化所有節點未被選過 12 dis[start] = 0; // 初始起點到起點距離為0 13 for (int i = 0; i < n - 1; i++) { 14 int minNode = -1; 15 // 選定一個節點: 16 // 1)未被選過; 17 // 2)距離最短; 18 for (int j = 0; j < n; j++) { 19 if (!visited[j] && ((minNode == -1) || (dis[j] < dis[minNode]))) {20 minNode = j; 21 } 22 } 23 // 對於已選擇的節點作為中轉站,重新整理經過中轉站到各節點的最短路徑 24 for (int j = 0; j < n; j++) { 25 dis[j] = std::min(dis[j], dis[minNode] + graph[minNode][j]); 26 } 27 visited[minNode] = true; 28 } 29 return dis; 30 } 31 32 void buildGraph(int n, vector<vector<int>> &graph) { 33 for (int i = 0; i < n; i++) { 34 for (int j = 0; j < n; j++) { 35 std::cin >> graph[i][j]; 36 } 37 } 38 } 39 void printGraph(const vector<vector<int>> &graph) { 40 for (const auto &vec : graph) { 41 for (const auto &val : vec) { 42 std::cout << val << " "; 43 } 44 std::cout << endl; 45 } 46 47 std::cout << endl; 48 } 49 50 int main() 51 { 52 FILE *fpIn; 53 fpIn = freopen("D:\\test.txt", "r", stdin); 54 if (fpIn == nullptr) { 55 std::cout << "freopen fail!" << endl; 56 } 57 int n = 0; 58 std::cin >> n; 59 vector<vector<int>> graph(n, vector<int>(n)); 60 // 構建無向帶權圖 61 buildGraph(n, graph); 62 // 列印無向圖 63 printGraph(graph); 64 // 遍歷列印n個節點作為中轉站時到各節點的最短距離陣列: 65 for (int i = 0; i < n; i++) { 66 int start = i; 67 std::cout << "start : " << start << endl; 68 std::cout << "dis[" << i << "]:"; 69 vector<int> dis = dijkstral(graph, start); 70 for (const auto &val : dis) { 71 std::cout << val << " "; 72 } 73 std::cout << endl; 74 } 75 fclose(fpIn); 76 system("pause"); 77 return 0; 78 }
驗證結果: