算法思路
路径矩阵
时间复杂度与空间复杂度
时间复杂度:因为核心算法是采用松弛法的三个for循环,因此时间复杂度为O(n^3)
空间复杂度:整个算法空间消耗是一个n*n的矩阵,因此其空间复杂度为O(n^2)
C++代码
// floyd.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include"iostream"
#include"fstream"
#define maxlen 20
#define maximum 100
using namespace std;
typedef struct graph
{
int vertex;
int edge;
int matrix[maxlen][maxlen];
};
int _tmain(int argc, _TCHAR* argv[])
{
ofstream outwrite;
outwrite.open("h.txt",ios::app|ios::out);
outwrite<<"welcome to the graph world!\n";
outwrite<<"the initial matrix is:\n";
int vertexnumber;
int edgenumber;
int beginning,ending,weight;
int mindistance[maxlen][maxlen];
int interval[maxlen][maxlen];
graph floydgraph;
cout<<"welcome to the graph world!"<<endl;
cout<<"input the number of the vertex: ";
cin>>vertexnumber;
cout<<"input the number of the edge: ";
cin>>edgenumber;
for (int i = 0; i < vertexnumber; i++)
{
for (int j = 0; j < vertexnumber; j++)
{
floydgraph.matrix[i][j]=maximum;
}
}
for (int i = 0; i <edgenumber; i++)
{
cout<<"please input the beginning index: ";
cin>>beginning;
cout<<"please input the ending index: ";
cin>>ending;
cout<<"please input the distance of the two dot: ";
cin>>weight;
floydgraph.matrix[beginning][ending]=weight;
}
for (int i = 0; i <vertexnumber; i++)
{
for (int j = 0; j < vertexnumber; j++)
{
mindistance[i][j]=floydgraph.matrix[i][j];
outwrite<<floydgraph.matrix[i][j]<<"\t";
interval[i][j]=-1;
}
outwrite<<"\n";
}
for (int k = 0; k <vertexnumber; k++)
{
for (int i = 0; i < vertexnumber; i++)
{
for (int j = 0; j < vertexnumber; j++)
{
if(mindistance[i][j]>mindistance[i][k]+mindistance[k][j])
{
mindistance[i][j]=mindistance[i][k]+mindistance[k][j];
interval[i][j]=k;
}
}
}
}
outwrite<<"\n"<<"after the floyd transition, the matrix is: "<<"\n";
for (int i = 0; i < vertexnumber; i++)
{
for (int j = 0; j < vertexnumber; j++)
{
cout<<"the mindistance between "<<i<<" and "<<j <<" is: ";
cout<<mindistance[i][j]<<endl;
cout<<"the two points pass through the point: "<<interval[i][j];
cout<<endl;
outwrite<<mindistance[i][j]<<"\t";
}
outwrite<<"\n";
}
outwrite<<"\n";
outwrite<<"the points between the beginning point and the ending point is:"<<"\n";
for (int i = 0; i < vertexnumber; i++)
{
for (int j = 0; j < vertexnumber; j++)
{
outwrite<<interval[i][j]<<"\t";
}
outwrite<<"\n";
}
outwrite.close();
getchar();
getchar();
getchar();
return 0;
}