• Dijkstra算法


    double dijkstra(int src, int dest, vector<int>& path, vector<map<int, double> >& adjT)
    {
        if (src < 0 || src >= adjT.size() || dest < 0 || dest >= adjT.size())
            return -1;
    
        map<int,int> previous; //记录最短路径上每个点的前驱点
        set<int> V; //未计算的点
        map<int, double> distance; //记录src到各顶点的距离
        int i;
        for (i=0; i<adjT.size(); i++) //初始化V和distance
        {
            V.insert(i);
            map<int,double>::const_iterator it = adjT[src].find(i);
            if (it != adjT[src].end())
                distance[i] = it->second;
            else
                distance[i] = DBL_MAX;
        }
        V.erase(src);
    
        for (int time=1; time<adjT.size(); time++)
        {
            for (int f=0; f<adjT.size(); f++)
                cout<<distance[f]<<' ';
            cout<<endl;
            double min = DBL_MAX;
            int v = src; //记录V中到src点最短的点
            for (set<int>::iterator it=V.begin(); it!=V.end(); ++it)
            {
                if (distance[*it] < min)
                {
                    min = distance[*it];
                    v = *it;
                }
            }
            V.erase(v); //
            
            for (set<int>::iterator it2=V.begin(); it2!=V.end(); ++it2) //更新距离表
                if (adjT[v].find(*it2) != adjT[v].end())
                {
                    const double newDist = distance[v] + adjT[v][*it2];
                    if (newDist < distance[*it2])
                    {
                        distance[*it2] = newDist;
                        previous[*it2] = v;
                    }
                }
        }
    
        //写入最短路径
        int prev = dest;
        while (prev != src)
        {
            prev = previous[prev];
            path.push_back(prev);
        }
        reverse(path.begin(), path.end());
        return distance[dest]; //返回最短距离
    }
  • 相关阅读:
    STM32的DMA
    stm32f1的IO,推挽与开漏
    STM32_GPIO配置及库函数讲解——独立按键
    STM32-外部中断学习笔记
    关于STM32的NVIC问题
    梯度下降<1>
    QString toInt()函数慎用
    linux→查看当前系统时间和修改系统当前时间
    oracle函数→数值型函数
    oracle函数→字符型函数
  • 原文地址:https://www.cnblogs.com/saieuler/p/2752391.html
Copyright © 2020-2023  润新知