1. 程式人生 > 其它 >任意兩點間最短路徑floyed演算法

任意兩點間最短路徑floyed演算法

 

1、無向帶權圖如下:

 

 2、採用floyed演算法手動計算出來的任意兩點間最短路徑陣列:

 

3、採用floyed演算法計算出來的任意兩點間的最短路徑:

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 constexpr int INF = 0x3F;
 7 
 8 int floyed(vector<vector<int>> &graph, int from, int to) {
 9     int n = graph.size();
10 if (from > n - 1 || to > n - 1) { 11 return -1; 12 } 13 for (int k = 0; k < n; k++) { 14 for (int i = 0; i < n; i++) { 15 for (int j = 0; j < n; j++) { 16 // 通過第k點作為中轉節點,找出最短路徑 17 graph[i][j] = std::min(graph[i][j], graph[i][k] + graph[k][j]);
18 } 19 } 20 } 21 return graph[from][to]; 22 } 23 24 void buildGraph(int n, vector<vector<int>> &graph) { 25 for (int i = 0; i < n; i++) { 26 for (int j = 0; j < n; j++) { 27 std::cin >> graph[i][j]; 28 } 29 }
30 } 31 void printGraph(const vector<vector<int>> &graph) { 32 for (const auto &vec : graph) { 33 for (const auto &val : vec) { 34 std::cout << val << " "; 35 } 36 std::cout << endl; 37 } 38 39 std::cout << endl; 40 } 41 42 int main() 43 { 44 FILE *fpIn; 45 fpIn = freopen("D:\\test.txt", "r", stdin); 46 if (fpIn == nullptr) { 47 std::cout << "freopen fail!" << endl; 48 } 49 int n = 0; 50 std::cin >> n; 51 vector<vector<int>> graph(n, vector<int>(n)); 52 // 構建無向帶權圖 53 buildGraph(n, graph); 54 // 列印初始無向圖帶權圖 55 printGraph(graph); 56 // 列印1到5的最短路徑: 57 std::cout << floyed(graph, 1, 5) << endl; 58 // 列印通過floyed演算法計算出來的任意兩個節點間的最短路徑圖: 59 printGraph(graph); 60 fclose(fpIn); 61 system("pause"); 62 return 0; 63 }

驗證執行結果: