图的Floyd算法求两点间的任意距离/C++

图的Floyd算法求两点间的任意距离

这里用到的图的存储结构为邻接矩阵

时间复杂度为O(n3)

Floyd算法实现如下

void Fluid(Graph g){
	for(int i =0 ;i <g->vex;i++)
		for(int j=0;j<g->vex;j++)
			for(int k=0;k<g->vex;k++)
				{
					if(g->marixWeight[j][i]!=0&&g->marixWeight[i][k]!=0&&j!=k)
					{
						int newDistance=g->marixWeight[j][i]+g->marixWeight[i][k];
						if (newDistance < g->marixWeight[j][k] || g->marixWeight[j][k] == 0)
                            g->marixWeight[j][k] = newDistance;
					}
				}	
}

打印邻接矩阵

printMarix(Graph g){
	for(int i =0;i<g->vex;i++)
	{
		int temp=0;
		for(int j=0;j<g->vex;j++ ){
		cout<<g->marixWeight[i][j]<<" ";
		temp+=	g->marixWeight[i][j];
		}
		 
		cout<<"路径和为"<<temp<<endl;
	}	
}

main函数展示

int main(){
	Graph graph = Create(4);//4为四个节点
	for (int c ='A';c<='D';++c)
		addVex(graph,(char)c);
	addEdge(graph,'A','B',8);
	addEdge(graph,'A','D',6);
	addEdge(graph,'B','C',4);
	addEdge(graph,'B','D',5);
	addEdge(graph,'C','D',3);
	printMarix(graph);
	Fluid(graph);
	
}
posted @ 2023-12-19 20:10  Happy_Eric  阅读(16)  评论(0编辑  收藏  举报