#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MaxSize 100
#define INF 1000001
int Graph[MaxSize][MaxSize];
/*弗洛伊德算法*/
void Floyd(int n)
{
int i,j,k;
//依次比较找出两个点之间的最短距离
for(k = 0;k < n;k++)
for(i = 0;i < n;i++)
for(j = 0;j < n;j++)
if(Graph[i][k] != INF && Graph[k][j] != INF && Graph[i][k] + Graph[k][j] < Graph[i][j])
Graph[i][j] = Graph[i][k] + Graph[k][j];
}
int main(int argc, char const *argv[]) {
int n,m,flag,i,j;
for(i = 0;i < n;i++)
for(j = 0;j < n;j++)
Graph[i][j] = INF;
//自己到自己为0
for(i = 0;i < n;i++)Graph[i][i] = 0;
printf("有向图-1 | 无向图-2:");
scanf("%d",&flag);
printf("请输入节点个数和边数:");
scanf("%d%d",&n,&m);
printf("请输入%d条边:\n",m);
for(i = 0;i < m;i++)
{
int a,b,len;
scanf("%d%d%d",&a,&b,&len);
Graph[a][b] = len;
if(flag == 2)
{
Graph[b][a] = len;
}
}
Floyd(n);
printf("-----------\n");
for(i = 0;i < n;i++)
{
for(j = 0;j < n;j++)
{
if(Graph[i][j] != INF)
printf("%d -> %d: %d |\n",i,j,Graph[i][j]);
}
printf("-----------\n");
}
return 0;
}
王道考研 ++++ Floyd 弗洛伊德算法
最新推荐文章于 2023-02-09 14:27:29 发布