数据来源:b站up主
视频:最短路径(三)Flodyd算法_哔哩哔哩_bilibili
#include <iostream>
using namespace std;
#define INF 0x3f3f3f3f
int edge[6][6] = { 0 };
int pre[6][6] = { 0 };
void flodyd(int k) {
for (int node = 1; node <= k; node++) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i == node || j == node) continue;
if (i == j) continue;
if (edge[i][node] + edge[node][j] < edge[i][j]) {
edge[i][j] = edge[i][node] + edge[node][j];
pre[i][j] = node;
}
}
}
}
return;
}
void output(int arr[][6], int k) {
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= k; j++) {
if (arr[i][j] == INF) cout << "~~" << " ";//~~代表无穷大
else printf("%2d ", arr[i][j]);
}
cout << endl;
}
return;
}
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
edge[i][j] = INF;
if (i == j) edge[i][j] = 0;
}
}
{
edge[1][2] = 10;
edge[2][3] = 50;
edge[3][5] = 10;
edge[1][4] = 30;
edge[1][5] = 100;
edge[4][5] = 60;
edge[4][3] = 20;
}
flodyd(5);
cout << "edge[][]:" << endl;
output(edge, 5);
printf("\n\n");
cout << "pre[][]:" << endl;
output(pre, 5);
return 0;
}
可以看到输出和视频中的一样