// Floyd.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui------
-------2015-2-16--------------------*/
//Floyd算法 最短路径
#include "stdafx.h"
#include "graph.h"
int P[NAX_VERTEX_NUM][NAX_VERTEX_NUM];//P[i][j]是顶点i到顶点j最短路径上的第一个顶点(起点和终点不计算在内)
unsigned int D[NAX_VERTEX_NUM][NAX_VERTEX_NUM];//D[i][j]是顶点i到顶点j最短路径总长度
void ShortestPath_FLOYD(MGraph G,int P[][NAX_VERTEX_NUM], unsigned int D[][NAX_VERTEX_NUM])
{
int v,w,u;
for(v=0; v<G.vexnum; v++) //各对结点之间初始已知路径及距离
{
for(w=0; w<G.vexnum; w++)
{
D[v][w] = G.arcs[v][w].adj;
P[v][w] = w;
}
}
for(u=0; u<G.vexnum; u++)
for(v=0; v<G.vexnum; v++)
for(w=0; w<G.vexnum; w++)
if(D[v][w] > D[v][u]+D[u][w])//从v经u到w的一条路径更短
{
D[v][w] = D[v][u]+D[u][w];
P[v][w] = P[v][u];
}
}
int main(int argc, char* argv[])
{
MGraph G;
CreateGraph(G);
ShortestPath_FLOYD(G,P,D);
int i ,j;
for(i=0; i<G.vexnum; i++)
{
for(j=0; j<G.vexnum; j++)
cout<<D[i][j]<<" ";
cout<<endl;
}
int k;
for(i=0; i<G.vexnum; i++)
for(j=0; j<G.vexnum; j++)
{
cout<<G.vexs[i]<<"->"<<G.vexs[j]<<"最短路径:"<<G.vexs[i]<<" ";
k = P[i][j];
while(k != j)
{
cout<<G.vexs[k]<<" ";
k = P[k][j];
}
cout<<G.vexs[k]<<endl;
}
return 0;
}
数据结构--Floyd算法
最新推荐文章于 2023-11-16 11:21:03 发布