找回密码
 立即注册

QQ登录

只需一步,快速开始

工控课堂 首页 工控文库 上位机编程 查看内容

Floyd(动态规划)求解任意两点间的最短路径(图解)

2022-7-10 13:01| 发布者: gk-auto| 查看: 409| 评论: 0

摘要: Floyd算法的精髓在于动态规划的思想,即每次找最优解时都建立在上一次最优解的基础上,当算法执行完毕时一定是最优解对于邻接矩阵w,w保存最初始情况下任意两点间的直接最短距离,但没有加入中继点进行考虑如w=20,即表示 ...

Floyd算法的精髓在于动态规划的思想,即每次找最优解时都建立在上一次最优解的基础上,当算法执行完毕时一定是最优解

对于邻接矩阵w,w保存最初始情况下任意两点间的直接最短距离,但没有加入中继点进行考虑
如w[1][2]=20,即表示点1与点2的当前最短距离(直接距离)为20

对于路径矩阵path,保存了点i到点j的最短路径中下一个点的位置,
如path[1][2]=0,表示1->2的路径中的下一个点为结点0

Floyd算法对所有中继点在任意两点中进行循环遍历.即k从0-n时考虑(i->k,k->j)的路径是否小于(i->j)的路,如果小于即更新邻接矩阵w的值与path矩阵中的值,使其始终保持最短
图解如下:

代码用例:

代码如下

#include<iostream> #include<fstream> #include<vector> using namespace std; const int MAX = 999; class Solution { public: void GetPath(vector<vector<int>>vec,int n) { vector<vector<int>>path(n); //初始化 for (int i = 0; i != n; i++) path[i].resize(n); for(int i=0;i!=n;i++) for (int j = 0; j != n; j++) { if (vec[i][j] != MAX)path[i][j] = j; else path[i][j] = -1; } for (int i = 0; i < n; i++)path[i][i] = -1; for(int k=0;k!=n;k++) for(int i=0;i!=n;i++) for (int j = 0; j != n; j++) { if (vec[i][k] + vec[k][j] < vec[i][j]) { vec[i][j] = vec[i][k] + vec[k][j]; path[i][j] = path[i][k]; } } for (int i = 0; i != n; i++) { cout << "\nStating from vertex: " << i << endl; bool flag = 0; for (int j = 0; j != n; j++) if (j != i && vec[i][j] < MAX) { flag = 1; cout << i << "->" << j << ":distance=" << vec[i][j] << ": " << i; int k = path[i][j]; while (k != j) { cout << "->" << k; k = path[k][j]; } cout << "->" << j << endl; } if (!flag)cout << "there's no path while starting from "<<i<<endl; } } }; int main() { ifstream putIn("D:\\Input.txt", ios::in); int num; int finalCount = 0; putIn >> num; const int x = num; vector<vector<int>>myVector(num); //myVector:带权邻接矩阵 for (int i = 0; i < num; i++) myVector[i].resize(num); for (int i = 0; i < num; i++) for (int j = 0; j < num; j++) { int temp; putIn >> temp; myVector[i][j] = temp; } Solution solution; cout << "Input文件中的邻接矩阵为\n"; for (auto x : myVector) { for (auto y : x)cout << y << '\t'; cout << endl; } solution.GetPath(myVector,num); return 0; }

关注公众号,加入500人微信群,下载100G免费资料!

最新评论

热门文章
关闭

站长推荐上一条 /1 下一条

QQ|手机版|免责声明|本站介绍|工控课堂 ( 沪ICP备20008691号-1 )

GMT+8, 2025-12-23 06:35 , Processed in 0.150741 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

返回顶部