6-3 最短路径(弗洛伊德算法)

6-3 最短路径(弗洛伊德算法) (15 分)
试实现弗洛伊德最短路径算法。

函数接口定义:

void ShortestPath_Floyed(AMGraph G);

其中 G 是基于邻接矩阵存储表示的有向图。

裁判测试程序样例:

#include <iostream>
using namespace std;

#define MaxInt 32767
#define MVNum 100

typedef char VerTexType; 
typedef int ArcType;

int Path[MVNum][MVNum];    
int D[MVNum][MVNum];

typedef struct{ 
    VerTexType vexs[MVNum];
    ArcType arcs[MVNum][MVNum];
    int vexnum,arcnum; 
}AMGraph;

void CreateUDN(AMGraph &G);//实现细节隐藏
void ShortestPath_Floyed(AMGraph G);

void DisplayPath(AMGraph G , int begin ,int temp ){
    if(Path[begin][temp] != -1){
        DisplayPath(G , begin ,Path[begin][temp]);
        cout << G.vexs[Path[begin][temp]] << "->";
    }
}

int main(){
    AMGraph G;
    char start , destination;
    int num_start , num_destination;
    CreateUDN(G);
    ShortestPath_Floyed(G);
    cin >> start >> destination;
    num_start = LocateVex(G , start);
    num_destination = LocateVex(G , destination);
    DisplayPath(G , num_start , num_destination);
    cout << G.vexs[num_destination]<<endl;
    cout << D[num_start][num_destination];
    return 0;
}
/* 请在这里填写答案 */

输入样例:
第1行输入结点数vexnum和边数arcnum。第2行输入vexnum个字符表示结点的值,接下来依次输入arcnum行,每行输入3个值,前两个字符表示结点,后一个数表示两个结点之间边的权值。最后一行输入源点及终点。

6 8
012345
0 5 100
0 2 10
0 4 30
1 2 5
2 3 50
3 5 10
4 3 20
4 5 60
0 5
结尾无空行
输出样例:
第一行输出源点到终点的最短路径,第二行输出源点到终点的最短路径距离。

0->4->3->5
60
结尾无空行
在这里插入图片描述

C++(g++)

void ShortestPath_Floyed(AMGraph G)
{
	int i,j,k,n=G.vexnum;
	for(i=0;i<n;++i)
	{
		for(j=0;j<n;++j)
		{
			D[i][j]=G.arcs[i][j];
			if(D[i][j]<MaxInt&&i!=j)
				Path[i][j]=i;//Path数组用来记录路径,
				//比如这个就表示从某一点出发到达j点需要经历i,这个顶点 
			else
				Path[i][j]=-1; 
		} 
	}
	for(k=0;k<n;++k)
	{
		for(i=0;i<n;++i)
		{
			for(j=0;j<n;++j)
			{
				if(D[i][k]+D[k][j]<D[i][j])
				{
					D[i][j]=D[i][k]+D[k][j];//更新最短距离 
					Path[i][j]=Path[k][j];//更改路径 
				} 
			} 
		} 
	} 
	
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微__凉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值