C++ implements Floyd algorithm
1. Principle
The Floyd algorithm is used to find the shortest distance between all vertices and can be applied to both directed and undirected graphs. The basic idea is to first use a matrix to store the direct path between each point, and then add each vertex in turn. Each time a vertex is added, the point is used as the intermediate point to calculate whether the path between each point passes through the intermediate point. It is shorter than the original one. If it is shorter, the path length is updated. After adding all the vertices, each data of the resulting matrix corresponds to the shortest path between two points.
2. Example
As shown in the figure, taking the undirected graph as example
1, the initial matrix dist is used to store the direct path distance of each point, dist[i][j] represents the distance from vi to vj, and the distance from each point to itself is 0. If the two points cannot Directly, the distance is Max. (Because it is an undirected graph here, dist[i][j] = dist[j][i])
2. Add the v0 point, because dist[2][0] + dist[0][3] = 5 <dist[2][3] = 6, so dist[2][3] = dist[3][2] = 5; in the same way, dist[2][0] + dist[0][1] = 3 <dist[2][1] = Max, so dist[2][1] = dist[1][2] = 3;
3. Continue to add the vertex update matrix. After all of them are added, the value of dist[i][j] in the resulting matrix is the shortest distance from vi to vj.
3. Code implementation
#include<iostream>
using namespace std;
#define Max 9999
int n, m;
int dist[Max][Max];
void Floyd()
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
for (int p = 0; p < n; ++p)
{
if (dist[j][p] > dist[j][i] + dist[i][p])
{
dist[j][p] = dist[j][i] + dist[i][p];
}
}
}
}
}
int main()
{
cout << "输入节点数: ";
cin >> n;
cout << "输入边数:";
cin >> m;
for (int i = 0; i < n; ++i)//初始化各个数组
{
for (int j = 0; j < n; ++j)
{
if (j == i)
{
dist[i][j] = 0;
}
else
{
dist[i][j] = Max;
}
}
}
int u, v, w;
cout << "输入各条边的信息:" << endl;
for (int i = 0; i < m; ++i)
{
cin >> u >> v >> w;
dist[u][v] = dist[v][u] = w;
}
Floyd();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << dist[i][j] << " \t";
}
cout << endl;
}
return 0;
}
Input and output information