问题描述
给出图,求任意两点的最短距离
算法思路
定义n+1个矩阵矩阵A,和记录路径的矩阵path
依次求A0~An的值,最后的An即为最短路径矩阵
// int A[8][7][7],path[7][7]; //A[v+1][i][j] 表示允许0~v的点为中间节点时,i到j的最短距离
A[0][i][j] = G[i][j]; //不允许中间节点时的最短距离就是邻接矩阵
循环:
A[v][i][j] = min(A[v][i][v] + A[v][v][j], A[v][i][j])
实现思路
比较简单,三个for循环即可。
源码
#include <iostream>
using namespace std;
#define MAX 32767
//Floyd算法 :全成对最短路径
//动态规划,每次加入一个点,允许他作为中间节点,更新最短距离矩阵
int main()
{
int n=7, v, i,j;
int G[7][7] = {
0,4,5,6,MAX,MAX,MAX,
4,0,3,MAX,1,MAX,MAX,
5,3,0,MAX,MAX,2,MAX,
6,MAX,MAX,0,2,MAX,MAX,
MAX,1,MAX,2,0,MAX,4,
MAX,MAX,2,MAX,MAX,0,3,
MAX,MAX,MAX,MAX,4,3,0
};
//------------------输入矩阵
//cout << "please input number of vertices:";
//cin >> n;
//cout << "now input the adjency matrix,if no edge,put it -1:";
//for (i = 0; i < n; i++)
// for (j = 0; j < n; j++)
// {
// cin >> G[i][j];
// if (G[i][j] == -1) G[i][j] = MAX;
// }
//------------------定义多个矩阵用来存放每次的最短路径矩阵A,和记录路径的矩阵path
int A[8][7][7],path[7][7]; //A[v+1][i][j] 表示允许0~v的点为中间节点时,i到j的最短距离
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
A[0][i][j] = G[i][j]; //不允许中间节点时的最短距离就是邻接矩阵
if (G[i][j]>0) path[i][j] = i;
else path[i][j] = -1;
}
//------------------循环,对于每个点v,遍历所有点对i,j,进行缩短操作
for (v = 0; v < n; v++)
{
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
if (A[v][i][j]>A[v][i][v] + A[v][v][j])
{
A[v+1][i][j] = A[v][i][v] + A[v][v][j];
path[i][j] = v;
}
else
{
A[v + 1][i][j] = A[v][i][j];
}
}
}
//------------------打印结果矩阵
//for (v = -1; v < n; v++)
//{
//cout << v << endl;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cout << A[n][i][j] << "\t";
cout << endl;
}
//}
while (1);
return 0;
}
遇到的小坑
1 .打印结果时应为n,写成了n+1
cout << A[n][i][j] << "\t";
2. if 后面忘了跟else
if (A[v][i][j]>A[v][i][v] + A[v][v][j])
{
A[v+1][i][j] = A[v][i][v] + A[v][v][j];
path[i][j] = v;
}
else
{
A[v + 1][i][j] = A[v][i][j];
}