欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

Dijkstra最短路径算法实现代码

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

Dijkstra的最短路径算法是基于前驱顶点的最短路径计算的,整体上来讲还是比较简单的,下面是代码:

复制代码 代码如下:

#include <iostream>
#include <vector>
#include <limits>

void shortestpath( const std::vector <std::vector< short> >& paths, int from, std::vector< short>& path){
    std:: vector<bool> flags(paths.size(), false);
    std:: vector<short> distance(paths.size(), 0);
    path.resize(paths.size(), 0);

    for(size_t i = 0; i != paths.size(); ++i){
        distance[i] = paths[from][i];
    }

    flags[from] = 1;

    int min, pos;
    for(size_t i = 1; i != paths.size(); ++i){
        pos = -1;
        min = std:: numeric_limits<short>::max();
        for(size_t j = 0; j != paths.size(); ++j){
            if(!flags[j] && distance[j] < min){
                min = distance[j];
                pos = j;
            }
        }

        if(pos == -1)
            break;

        flags[pos] = true;

        for(size_t j = 0; j != paths.size(); ++j){
            if(!flags[j] && paths[pos][j] != 0
                && paths[pos][j] < std::numeric_limits <int>:: max()
                && min+paths[pos][j] < distance[j]){
                distance[j] = min + paths[pos][j];
                path[j] = pos;
            }
        }
    }

    for(size_t i = 0; i != distance.size(); ++i){
        std::cout << distance[i] << " " << std::flush;
    }
    std::cout << std:: endl;
}

int main(){
    std::cout << "请输入顶点数:" << std::flush;
    int sum; std::cin >> sum;
    std:: vector<std::vector <short> > paths;
    for(int i = 0; i != sum; ++i){
        paths.push_back(std:: vector<short>(sum, std::numeric_limits< short>::max()));
        paths[i][i] = 0;
    }

    std::cout << "请输入边数:" << std::flush;
    std::cin >> sum;

    int vi, vj, weight;
    for(int i = 0; i != sum; ++i){
        std::cin >> vi >> vj >> weight;
        paths[vi][vj] = weight;
        paths[vj][vi] = weight;
    }

    std:: vector<short> path;
    shortestpath(paths, 0, path);

    std::cout << "最近路径结果为:" << std::flush;
    for(size_t i = 0; i != path.size(); ++i){
        std::cout << path[i] << " " << std::flush;
    }
    std::cout << std:: endl;

    return 0;
}

上一篇:纯C语言:分治假币问题源码分享

栏    目:C语言

下一篇:linux c语言操作数据库(连接sqlite数据库)

本文标题:Dijkstra最短路径算法实现代码

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/3844.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有