使用地图的Dijsktra算法不能正确添加值

时间:2015-12-15 04:12:18

标签: c++ algorithm maps dijkstra

我创建了一个使用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();

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

1 个答案:

答案 0 :(得分:2)

使用

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

而不是

<table class="T1">
<tr>
<td>
<table class="T2"></table>
<table class="T3">
  <tr><td class="Td31">Text</td>
       <td class="Td32"><div class="repetableimg1">image1</div>
                        <div class="repetableimg2">image2</div>
       </td></tr>
</table>
<table class="T4"></table>
</td>
</tr>
</table>