C++中最短路径算法(Floyd)

首先是时间复杂度为O(n^3)的多源最短路径算法Floyd.

详细算法原理请参照https://blog.csdn.net/mgsky1/article/details/77998422

#include 
#include
#include
using namespace std;
/*多源最短路径问题floyd算法*/
void print(int **path, int &v1, int v2);
void display(int **path);
int n;
int main()
{
	cout << "please input the number of graph." << endl;
	cin >> n;
	int **flag=new int *[n], **weight=new int *[n];
	for (int i = 0; i < n; ++i)
	{
		flag[i] = new int[n];
		weight[i] = new int[n];
		cout << "please input weight[" << i << "]:";
		for (int j = 0; j < n; ++j)
		{
			flag[i][j] = -1;
			cin >> weight[i][j];
		}
	}
	for (int k = 0; k < n;++k)
	for (int i = 0; i < n;++i)
	for (int j = 0; j < n;++j)
	if (weight[i][j] == 0 && (weight[i][k] * weight[k][j] == 0))
		continue;
	else if(weight[i][j]>weight[i][k] + weight[k][j])
	{
		weight[i][j] = weight[i][k] + weight[k][j];
		flag[i][j] = k;
	}
	display(flag);
	int v1, v2;
	cout << "please input two vertice:";
	cin >> v1 >> v2;
	if (flag[v1][v2] == -1 && weight[v1][v2] == 0)
		cout << "That's is not exist a path from " << v1 << "->" << v2 << endl;
	else
	{
		cout << "The path of " << v1 << "->" << v2 << " is:\n" << v1 << "->";
		print(flag, v1, v2);
	}
	for (int t = 0; t < n; ++t)
	{
		delete[] flag[t];
		delete[] weight[t];
	}
	delete[] flag;
	delete[] weight;
	system("pause");
	return 0;
}
void display(int **path)
{
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			cout.setf(ios::right, ios::adjustfield);
			cout << setw(2) << path[i][j];
		}
		cout << endl;
	}	
}
void print(int **path, int &v1, int v2)
{
	if (path[v1][v2] == -1)
		cout << v2 << endl;
	else
	{
		cout << path[v1][v2] << "->";
		int mid = path[v1][v2];
		print(path, mid, v2);
	}
	return;
}

代码测试结果如下:

C++中最短路径算法(Floyd)_第1张图片

你可能感兴趣的:(数据结构与算法)