在Floyd算法中,我们需要通过每一个点对两个点进行连接,以此求出两点之间的最短路,因此,我们要遍历每一个点
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
int MAP[MAXN][MAXN];
int n, m;
void Floyd()
{
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(MAP[i][j] > MAP[i][k] + MAP[k][j])
MAP[i][j] = MAP[i][k] + MAP[k][j];
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(i == j) MAP[i][j] = 0;
else MAP[i][j] = INF;
int a, b, c;
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &a, &b, &c);
MAP[a][b] = MAP[b][a] = c;
}
Floyd();
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
printf("%d ", MAP[i][j]);
}
printf("\n");
}
}
return 0;
}
某些细节可以是适当更改