1.问题整体复制,让你更快的找到我
【问题描述】
对于下面一张若干个城市,以及城市之间距离的地图,请采用弗洛伊德算法求出所有城市之间的最短路径。
【输入形式】
顶点个数n,以及n*n的邻接矩阵,其中不可达使用9999代替
【输出形式】
每两个顶点之间的最短路径和经过的顶点
注意:顶点自身到自身的dist值为0,path则为该顶点的编号
【样例输入】
4
9999 4 11 9999
6 9999 2 9999
1 9999 9999 1
9999 3 9999 9999
【样例输出】
from 0 to 0: dist = 0 path:0
from 0 to 1: dist = 4 path:0 1
from 0 to 2: dist = 6 path:0 1 2
from 0 to 3: dist = 7 path:0 1 2 3
from 1 to 0: dist = 3 path:1 2 0
from 1 to 1: dist = 0 path:1
from 1 to 2: dist = 2 path:1 2
from 1 to 3: dist = 3 path:1 2 3
from 2 to 0: dist = 1 path:2 0
from 2 to 1: dist = 4 path:2 3 1
from 2 to 2: dist = 0 path:2
from 2 to 3: dist = 1 path:2 3
from 3 to 0: dist = 6 path:3 1 2 0
from 3 to 1: dist = 3 path:3 1
from 3 to 2: dist = 5 path:3 1 2
from 3 to 3: dist = 0 path:3
2.不多废话,先复制代码
#include<iostream>
using namespace std;
const int size1 = 100;
const int big = 9999;
typedef struct grap
{
int edge[size1][size1];
int nump;
int nume;
}grape;
void creat(grape& G)
{
cin >> G.nump;
for (int i = 0; i < G.nump; i++)
{
for (int j = 0; j < G.nump; j++)
{
cin >> G.edge[i][j];
G.nume++;
}
}
}
void shortpath(int path[][size1], int i, int j)
{
int k = path[i][j];
if (k)
{
shortpath(path, i, k);
cout << k << ' ';
shortpath(path, k, j);
}
}
void fl(grape g)
{
int dis[size1][size1];
int path[size1][size1];
for (int i = 0; i < g.nump; i++)
{
for (int j = 0; j < g.nump; j++)
{
dis[i][j] = g.edge[i][j];
path[i][j] = 0;
}
dis[i][i] = 0;
}
for (int k = 0; k < g.nump; k++)
{
for (int i = 0; i < g.nump; i++)
{
if (dis[i][k] < big)
{
for (int j = 0; j < g.nump; j++)
{
if (dis[i][k] + dis[k][j] < dis[i][j])
{
dis[i][j] = dis[k][j] + dis[i][k];
path[i][j] = k;
}
}
}
}
}
for (int i = 0; i < g.nump; i++)
{
for (int j = 0; j < g.nump; j++)
{
if (dis[i][j] == 0) cout << "from " << i << " to " << j << ": dist = 0 path:" << i << endl;
else
{
cout << "from " << i << " to " << j << ": dist = " << dis[i][j];
cout << " path:" << i << " ";
shortpath(path, i, j);
cout << j << endl;
}
}
}
}
int main()
{
grape g;
creat(g);
fl(g);
return 0;
}
3.简单聊聊思想
首先解释一下变量们,size1代表数组的长度,big代表没有权值时的矩阵初始化,结构体grape代表图,edge代表零阶矩阵,nump代表顶点数量 ,nume代表边的数量,creat函数代表初始化grape数组,然后是主要函数fl,dis数组存储的是距离,dis[i][j]代表从i到j的最短距离,path数组存储着路径,path[i][j]表示从i到j的最短路径之间的顶点,首先将dis数组初始化为每条边的值,再将path数组初始化为0,再将dis数组的主对角线赋值为0,因为自己到自己的距离为0,然后对零阶矩阵进行遍历,如果两个点之间的距离不是big,表示着两个点之间有边,则以边的终点为起点进行探索,遍历各个顶点,如果原边的距离+原边终点到某顶点的距离小于原边的起点到某顶点的距离,则对对应的dis数组与path数组进行更新,然后就是打印函数,为从i到j的打印函数,如果该点的dis为0,也就是主对角线,直接打印,否则在直接打印部分数据的基础上,还需要调用打印函数shortpath,也就是一个简单递归函数