您的位置:首页 > 其它

floyd最短路径算法2,求出经过哪些路径

2017-03-11 17:36 281 查看
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<algorithm>
using namespace std;

//最短路径算法 2
//数组的下标从0开始,但是算法下标从1开始,所以将数组0位的空着,方便理解。
int W[6][6];
int D[6][6];//最后的最短路径结果

int P[6][6];//从V_i到V_j最短路径上一个中间顶点的**最高**索引(若至少存在一个中间顶点)
//若不存在中间顶点则为0
void floyd(int n,int D[][6],int P[][6])
{
for(int k=1;k<=n;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(D[i][j]>D[i][k]+D[k][j])
{
D[i][j]=D[i][k]+D[k][j];
P[i][j]=k;//这个地方+1是因为下标的缘故
}

}
}
}
}

void path(int q,int r)
{
if(P[q][r]!=0)
{
path(q,P[q][r]);
cout<<"v"<<P[q][r];
//path(P[q][r],r);
}
}

int main()
{
int n=5;
cout<<"输入邻接矩阵"<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>W[i][j];
}
}
memset(P,0,sizeof(int));
memcpy(D,W,sizeof(int)*36);
floyd(n,D,P);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<D[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<P[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
path(5,3);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  floyd算法