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]; //返回最短距离
}

posted on 2012-11-03 12:35  赛欧拉  阅读(188)  评论(0编辑  收藏  举报