该算法适用于正权值的图,用于解决单源点最短路径问题。用到了贪心的思想,需要一个dis数组来保存源点到其余各顶点的最短距离,一共(n-1)轮大循环,每次大循环都要确定一个离源点最近且没有被访问过的顶点,通过该顶点来进行“松弛”,该顶点作为中转点,看其余顶点通过该中转点是否比直接到源点更近,如果更近,则更新最短距离。
/*
6
0 1 12 1000 1000 1000
1000 0 9 3 1000 1000
1000 1000 0 1000 5 1000
1000 1000 4 0 13 15
1000 1000 1000 1000 0 4
1000 1000 1000 1000 1000 0
0 3
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int vis[N];
int dis[N];
int mp[N][N]; // 邻接矩阵
int start, end;
int n;
void input() {
cout << "请输入顶点数:\n";
cin >> n;
cout << "请输入邻接矩阵:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> mp[i][j];
}
}
}
void dijkstra() {
cout << "请输入源点:\n";
cin >> start;
vis[start] = 1;
for (int i = 0; i < n; i++) {
dis[i] = mp[start][i];
}
int cnt = 1;
while (cnt != n) { // 每次确定一个顶点,一共是(n-1)轮循环
int min_dis = INT_MAX, index;
for (int i = 0; i < n; i++) {
if (!vis[i] && dis[i] < min_dis) {
min_dis = dis[i];
index = i;
}
}
vis[index] = 1;
for (int i = 0; i < n; i++) {
if (mp[index][i] != 1000 && i != index) { // 与中转点相邻的点
if (dis[index] + mp[index][i] < dis[i]) {
dis[i] = dis[index] + mp[index][i];
}
}
}
cnt++;
}
}
void output() {
cout << "请输入终点编号(从0开始编号):\n";
cin >> end;
cout << "最短距离为:" << dis[end] << endl;
}
int main() {
input();
dijkstra();
output();
return 0;
}