#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
const int INF = INT_MAX;
void Dijkstra(int n, int s, vector<vector<int>> graph, vector<bool> &visited,
vector<int> &dist, vector<int> &path) {
/*
* n: 顶点个数
* s: 源点
* graph: 图的邻接矩阵
* visited: 标记顶点是否已经在集合中
* dist: 源点s到其他顶点的最短距离
* path: 存放最短路径中当前顶点的前驱顶点
*/
// 初始化
fill(visited.begin(), visited.end(), false);
fill(path.begin(), path.end(), s);
for (int i = 0; i < n; i++) {
dist[i] = graph[s][i];
}
dist[s] = 0;
for (int i = 0; i < n; i++) {
// 找出不在集合中的距离s最近的顶点u
int u = -1;
int min = INF;
for (int j = 0; j < n; j++) {
if (!visited[j] && dist[j] < min) {
u = j;
min = dist[u];
}
}
// 找不到小于INF的dist[u],说明剩下的顶点与起点s不连通
if (u == -1) {
return;
}
// 找到了u,则加入集合
visited[u] = true;
// 遍历所有顶点,如果v未在集合中 && 可以通过u访问v && 通过u访问v使得dist[v]更小
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v]; // 更新dist[v]
path[v] = u; // 记录u为v的前驱顶点
}
}
}
}
// printPath辅助函数
void printPath_t(int s, int v, vector<int> path) {
if (v == s) {
cout << s << " ";
return;
}
printPath_t(s, path[v], path);
cout << v << " ";
}
// 输出从起点s到顶点v的最短路径
void printPath(int s, int v, vector<int> path, vector<int> dist) {
if (dist[v] == INF) {
cout << "顶点" << s << "到顶点" << v << "不可达" << endl;
return;
}
cout << "The shortest path between " << s << " and " << v << " is: ";
printPath_t(s, v, path);
cout << endl;
}
int main() {
int n = 6;
int s = 0;
vector<vector<int>> graph = {{ 0, 4,INF,INF, 1, 2},
{ 4, 0, 6,INF,INF, 3},
{INF, 6, 0, 6,INF, 5},
{INF,INF, 6, 0, 4, 5},
{ 1,INF,INF, 4, 0, 3},
{ 2, 3, 5, 5, 3, 0}};
vector<int> dist(n);
vector<int> path(n);
vector<bool> visited(n);
Dijkstra(n, s, graph, visited, dist, path);
for (int i = 0; i < n; i++) {
if (i != s) {
cout << "The shortest distance between " << s << " and " << i
<< " is: " << dist[i] << endl;
printPath(s, i, path, dist);
cout << endl;
}
}
return 0;
}
运行结果:
The shortest distance between 0 and 1 is: 4
The shortest path between 0 and 1 is: 0 1
The shortest distance between 0 and 2 is: 7
The shortest path between 0 and 2 is: 0 5 2
The shortest distance between 0 and 3 is: 5
The shortest path between 0 and 3 is: 0 4 3
The shortest distance between 0 and 4 is: 1
The shortest path between 0 and 4 is: 0 4
The shortest distance between 0 and 5 is: 2
The shortest path between 0 and 5 is: 0 5