【问题标题】:Dijsktra's algorithm using maps is not adding values correctly使用地图的 Dijkstra 算法未正确添加值
【发布时间】:2015-12-15 04:12:18
【问题描述】:

我为 Dijkstra 的最短路径算法创建了一个使用地图的函数。我接近让它正常工作,但我目前被卡住了。我知道地图不是最有效的,甚至也不是最常用的,所以这样做是为了更好地理解地图。我相信我几乎所有东西都是正确的,但似乎无法迭代并写入距离向量中的正确位置。这是代码:

void Graph::dikAlgorithm(string start, string finish)
{
    nodeAmount = mapData.size();
    vector<double> costVec(nodeAmount);
    vector<bool> vis(nodeAmount);

    vector<map<string, double>> keys;
    for (auto& kv : mapData)
    {
        keys.push_back(kv.second);
    }

    int staIndex = distance(mapData.begin(), mapData.find(start));
    int finIndex = distance(mapData.begin(), mapData.find(finish));

    //initialize the distance vector to infinity
    for (int i = 0; i < nodeAmount; ++i)
    {
        costVec[i] = INFINITY;
        vis[i] = false;
    }

    //starting city distance is set to zero
    costVec[staIndex] = 0;

    for (int i = 0; i < nodeAmount; ++i)
    {
        int cur = -1;
        for (int j = 0; j < nodeAmount; ++j)
        {
            //if visited node has been visted, continue incrementing j
            if (vis[j]) continue;

            //once an unvisted node has been reached, check to see if next is less than current
            if (cur == -1 || costVec[j] < costVec[cur])
            {
                cur = j;
            }
        }

        //set the visited node to solved
        vis[cur] = true;

        map<string, double>::iterator tempMap = keys[cur].begin();

        //add the total distance using maps and vectors
        for (int j = 0; j < keys[cur].size() - 1; j++)
        {
            double tempCost = tempMap->second;
            double pathCost = costVec[cur] + tempCost;
            if (pathCost < costVec[j])
            {
                costVec[distance(mapData.begin(), mapData.find(tempMap->first))] = pathCost;
            }
            tempMap++;
        }
    }
    double answer = costVec[finIndex];
    cout << "The least amount of money from " << start << " to " << finish << "    is " << answer << endl;
}

我相信错误是在这行之后发生的

     map<string, double>::iterator tempMap = keys[cur].begin();

此错误导致距离矢量无法正确添加。因此,我通常会从地图中得到一个随机值,即最短路径,甚至无穷大。 任何帮助将不胜感激。如果您需要更多详细信息,请随时问我。

【问题讨论】:

    标签: c++ algorithm maps dijkstra


    【解决方案1】:

    使用

    map<string, double>::iterator tempMap;
    tempMap = keys.begin();
    

    而不是

    map<string, double>::iterator tempMap = keys[cur].begin();
    

    【讨论】:

    • 它抛出一个错误,说没有与这些操作数匹配的运算符。你的意思是你希望它在每次通过循环时迭代到一个新的键?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2017-04-04
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多