最短的路线修改

时间:2016-11-29 20:27:19

标签: c++ function dijkstra

有没有办法修改它来显示最短路径的路线?例如,如果我有一个数字列表,如(3,1),(3,0),(4,3),(2,1),从4到1的输出将是4> 3, 3→1

// Prints shortest paths from src to all other vertices
void Graph::shortestPath(int src)
{
    // Create a priority queue to store vertices that
    // are being preprocessed. This is weird syntax in C++.
    // Refer below link for details of this syntax
    // http://geeksquiz.com/implement-min-heap-using-stl/
    priority_queue< iPair, vector <iPair> , greater<iPair> > pq;


    // Create a vector for distances and initialize all
    // distances as infinite (INF)
    vector<int> dist(V, INF);

    // Insert source itself in priority queue and initialize
    // its distance as 0.
    pq.push(make_pair(0, src));
    dist[src] = 0;

    /* Looping till priority queue becomes empty (or all
      distances are not finalized) */
    while (!pq.empty())
    {
        // The first vertex in pair is the minimum distance
        // vertex, extract it from priority queue.
        // vertex label is stored in second of pair (it
        // has to be done this way to keep the vertices
        // sorted distance (distance must be first item
        // in pair)
        int u = pq.top().second;
        pq.pop();

        // 'i' is used to get all adjacent vertices of a vertex
        list< pair<int, int> >::iterator i;
        for (i = adj[u].begin(); i != adj[u].end(); ++i)
        {
            // Get vertex label and weight of current adjacent
            // of u.
            int v = (*i).first;
            int weight = (*i).second;

            //  If there is shorted path to v through u.
            if (dist[v] > dist[u] + weight)
            {
                // Updating distance of v
                dist[v] = dist[u] + weight;
                pq.push(make_pair(dist[v], v));
            }
        }
    }

    // Print shortest distances stored in dist[]
    printf("Vertex   Distance from Source\n");
    for (int i = 0; i < V; ++i)
            printf("%d \t\t %d\n", i, dist[i]);
    }

放入一个存储路径数量的数组,如4,3,3,1(使用上面的示例)似乎是最好的想法,但我不知道在此代码中插入数组的位置这一点。

2 个答案:

答案 0 :(得分:0)

听起来像是一个家庭作业问题。

如果这是DFS,那么存储路径编号的想法会很棒。不幸的是,Djikstra的算法并不像DFS那样自然地跟踪路径;它只需要下一个最近的节点并更新距离值。在这方面,它可能更像是BFS。

你可以做的是当你更新到每个节点的距离时,以某种方式存储你来自哪个节点(如果你被允许,可能在你的iPair结构中,可能在地图/数组中)你有办法识别你的节点)。为了这篇文章,我将它称为“来自”参考。然后,每次找到节点的较短路径时,您也可以从引用中更新它。

那么如何找到给定节点的路径呢?简单:只需从结束节点开始,然后按照“from”引用返回源。

答案 1 :(得分:0)

就像保存dist向量中每个顶点的距离一样,将最后更新它的前任顶点保存在名为predecessor的向量中。

vector<int> dist(V, INF);
vector<int> predecessor(V, 0);

然后,每当您更新距离时,请更新前一个:

dist[v] = dist[u] + weight;
predecessor[v] = u;

最后,您可以追踪最短路径(向后)到源的任何顶点:

printf("Vertex   Distance from Source      shortest path from source\n");
for (int i = 0; i < V; ++i)
{
        printf("%d \t\t %d\t\t", i, dist[i]);
        int j = i;
        do
        {
             printf("%d,", j);
             j = predecessor[j];
        } while(j != src);
        printf("\n");
}