Example of C++ implementation of the multi source shortest path Floyd algorithm
- 2020-05-27 06:34:19
- OfStack
In this paper, an example of C++ implementation of the multi-source shortest path Floyd algorithm is presented. I will share it with you for your reference as follows:
#include<cstdio>
#include<cstring>
#include<iostream>
#define MAX 999
using namespace std;
int n,m;
int e[MAX][MAX];
void Init()
{
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
{
if(i==j)
e[i][j]=0;
else
e[i][j]=MAX;
}
}
void Input()
{
int a,b,c;
for(int i=1; i<=m; ++i)
{
cin>>a>>b>>c;
e[a][b]=c;
}
}
void Floyd()
{
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(e[i][j]>e[i][k]+e[k][j])
e[i][j]=e[i][k]+e[k][j];
}
void Output()
{
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
cout<<"dis["<<i<<"]["<<j<<"] = "<<e[i][j]<<endl;
}
int main()
{
while(1)
{
cout<<"n"<<endl;// The number of vertices
cin>>n;
if(!n) break;
cout<<"m"<<endl;// The number of edges
cin>>m;
Init();
Input();
Floyd();
Output();
}
}
Floyd algorithm is an algorithm to find the shortest path of multiple points, and its core code is
void Floyd()
{
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(e[i][j]>e[i][k]+e[k][j])
e[i][j]=e[i][k]+e[k][j];
}
I hope this article is helpful to you C++ programming.