C++实现Floyd算法(路径+长度)

 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

结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值