数据结构:最短路径算法之Floyed算法

Floyed算法

Floyed-Warshall 算法用来找出每对点之间的最短距离。它需要用邻接矩阵来储存边,这个算法通过考虑最佳子路径来得到最佳路径。 注意单独一条边的路径也不一定是最佳路径。

时间复杂度O(n^3),只要有存下邻接矩阵的空间,时间一般没问题,并且不必担心负权边的问题。

代码如下

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using namespace std;

const int MAX = 1000000;
// floyed算法可以计算得到任意的i到j的最短路径

/*
6 个节点
1000000 1000000 10 100000 30 100
1000000 1000000 5 1000000 1000000 1000000
1000000 1000000 1000000 50 1000000 1000000
1000000 1000000 1000000 1000000 1000000 10
1000000 1000000 1000000 20 1000000 60
1000000 1000000 1000000 1000000 1000000 1000000

结果
D[0]   D[1]   D[2]   D[3]   D[4]   D[5]
0   1000000   10     50     30     60

//节点0到节点5的最短路径是0 4 3 5
*/

void floyd()
{
    const int n = 6;
    int mat[6][6] =
    {
        1000000, 1000000, 10, 100000, 30, 100,
        1000000, 1000000, 5, 1000000, 1000000, 1000000,
        1000000, 1000000, 1000000, 50, 1000000, 1000000,
        1000000, 1000000, 1000000, 1000000, 1000000, 10,
        1000000, 1000000, 1000000, 20, 1000000, 60,
        1000000, 1000000, 1000000, 1000000, 1000000, 1000000 };

    int flag[6][6] = { 0 };
    //访问标志初始化
    for (int i = 0; i<n; i++)
        for (int j = 0; j<n; j++)
            flag[i][j] = -1;

    for (int k = 0; k<n; k++)
    {
        for (int i = 0; i<n; i++)
        {
            for (int j = 0; j<n; j++)
            {
                if (mat[i][j] <= MAX && mat[i][k] + mat[k][j] < mat[i][j])
                {
                    mat[i][j] = mat[i][k] + mat[k][j];
                    flag[i][j] = k;
                }
            }
        }
    }
    for (int i = 0; i<n; i++)
        cout << mat[0][i] << "  ";
    cout << endl;

    //打印beg到end的最短路径节点信息
    int beg = 0, end = n - 1;
    int next = flag[beg][end];
    cout << beg << " -> ";
    while (next != -1)
    {
        cout << next << " -> ";
        next = flag[next][end];
    }
    cout << end << endl;

}
int main()
{
    floyd();
    system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值