Floyd多源最短路,时间复杂度为O(n^3)。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
#define N 1000
int dist[N][N];
int A[N][N];
int path[N][N];
stack<int> Q;
void show_path(int m, int n);
int main()
{
int n;
cout << "Please enter the number of vertex in your graph:" << endl;
cin >> n;
cout << "Please enter your graph as a matrix:" << endl;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> A[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
dist[i][j] = A[i][j];
path[i][j] = i;
}
for (int k=1;k<=n;k++)
for (int i=1;i<=n;i++)
for (int j = 1; j <= n; j++)
if (dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j] = k;
}
for (int i=1;i<=n;i++)
for (int j = 1; j <= n; j++)
{
cout << i << "->" << j << "length: " << dist[i][j] << " " << "path: ";
show_path(i, j);
}
system("pause");
return 0;
}
void show_path(int m, int n)
{
int k = n;
while (!Q.empty())
Q.pop();
while (k != m)
{
Q.push(k);
k = path[m][k];
}
Q.push(m);
while (!Q.empty())
{
cout << Q.top() << " ";
Q.pop();
}
cout << endl;
return;
}
实例验证(用邻接矩阵表示图):
7个点的图:
0 12 1000 1000 1000 16 14
12 0 10 1000 1000 7 1000
1000 10 0 3 5 6 1000
1000 1000 3 0 4 1000 1000
1000 1000 5 4 0 2 8
16 7 6 1000 2 0 9
14 1000 1000 1000 8 9 0
结果: