Dijkstra算法,求单源最短路径(包含路径)
2015-08-23 15:30
411 查看
图片是拷贝过来的。
引用下别人的图片,方便以后回顾算法。
dijstra_sample.txt
5
7
1 2 10
1 4 30
1 5 100
2 3 50
3 5 10
4 3 20
4 5 60
#include <iostream> using namespace std; const int maxnum = 100; const int maxint = 999999; int dist[maxnum]; // 表示当前点到源点的最短路径长度 int pre[maxnum]; // 记录当前点的前一个结点 int cost[maxnum][maxnum]; // 记录图的两点间路径长度 bool vistied[maxnum]; void Dijkstra(int n, int v0) { memset(pre,0,sizeof(pre)); memset(vistied, 0, sizeof(vistied); for (int i = 1; i <= n; i++) { dist[i] = cost[v0][i]; if (dist[i] == maxint) { pre[i] = 0; } else pre[i] = 1; } vistied[v0] = true; dist[v0] = 0; //循环n-1次 for (int i = 2; i <= n; i++) { int min = maxint; int u; for (int j = 1; j <= n; j++) { if (!vistied[j] && min>dist[j]) { min = dist[j]; u = j; } } vistied[u] = true; //更新dist for (int j = 1; j <= n; j++) { if (!vistied[j] && min + cost[u][j] < dist[j]) { dist[j] = min + cost[u][j]; pre[j] = u; } } } } void searchPath(int u, int v) { int path[maxnum]; memset(path,0,sizeof(path)); int index = 1; path[index++] = v; int tmp = pre[v]; while (tmp != u) { path[index++] = tmp; tmp = pre[tmp]; } path[index] = u; for (int i = index; i >= 1; i--) { cout << path[i] << " "; } } int main() { freopen("dijstra_sample.txt", "r", stdin); // 各数组都从下标1开始 int n, line; // 图的结点数和路径数 // 输入结点数 cin >> n; // 输入路径数 cin >> line; int p, q, len; // 输入p, q两点及其路径长度 // 初始化c[][]为maxint for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) cost[i][j] = maxint; for (int i = 1; i <= line; ++i) { cin >> p >> q >> len; if (len < cost[p][q]) // 有重边 { cost[p][q] = len; // p指向q cost[q][p] = len; // q指向p,这样表示无向图 } } for (int i = 1; i <= n; ++i) dist[i] = maxint; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) printf("%8d", cost[i][j]); printf("\n"); } Dijkstra(n, 1); // 最短路径长度 cout << "源点到最后一个顶点的最短路径长度: " << dist << endl; // 路径 cout << "源点到最后一个顶点的路径为: "; searchPath(1, n); }
相关文章推荐
- c++中静态成员变量要在类外部再定义,否则产生link2001错误
- 10到10000中的0的个数
- 三周工作日志
- U-Boot 第二阶段代码分析
- oracle迁移表空间数据文件
- 23种设计模式全解析
- 杂谈: 房产信息泄露谁是内鬼?
- iOS UI基础-4.1应用程序管理 字典转Model
- Java动态代理
- oracle迁移表空间数据文件
- django+apache部署
- 简单纯js实现点击切换TAB标签实例
- ueditor1-4-3 编辑器使用教程
- Sftp和ftp 区别、工作原理等
- Maximum Value(哈希)
- mysql数据表的连接实例
- 基于网页的认证跳转实现
- Effective C++ 条款17 以独立语句将newed对象置入智能指针
- Maximum Value(哈希)
- Dom第四天学习总结