Dijikstra计算后如何打印路径?

时间:2017-02-01 09:11:22

标签: c++ algorithm dijkstra

我开始实现Graphs算法,我不知道如何打印Dijkstra实现的从源到目标的路径? 谢谢

#define INF 0x3f3f3f3f
typedef pair<int,int> ii;  // to vertex, weight
typedef vector<ii> vii;    // from source to vertexes with weight
typedef vector<vii> graph;  // graph

graph gg;
vector<int> Dist;

void Dijikstra(int source, int N){
    priority_queue<ii, vii, greater<ii>> Q;
    Dist.assign(N,INF);
    Dist[source] = 0;
    Q.push(make_pair(0,source));
    while (!Q.empty())
    {
        ii front = Q.top(); Q.pop();
        int d = front.first, u = front.second;
        if(d > Dist[u]) continue;
        for (int i = 0; i < gg[u].size(); i++)
        {
            ii v = gg[u][i];
            if(Dist[u]+v.second < Dist[v.first]){
                Dist[v.first]  = Dist[u] + v.second;
                Q.push(ii(Dist[v.first],v.first));          
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

Dijkstra算法的伪代码:

function Dijkstra(Graph, source):
    create vertex set Q
    for each vertex v in Graph:  // Initialization
        dist[v] ← INFINITY       // Unknown distance from source to v
        prev[v] ← UNDEFINED      // Previous node in optimal path from source
        add v to Q               // All nodes initially in Q (unvisited nodes)
    dist[source] ← 0             // Distance from source to source
    while Q is not empty:
        u ← vertex in Q with min dist[u]  // Node with the least distance will be selected first
        remove u from Q     
        for each neighbor v of u:         // where v is still in Q.
            alt ← dist[u] + length(u, v)
            if alt < dist[v]:             // A shorter path to v has been found
                dist[v] ← alt 
                prev[v] ← u 
     return dist[], prev[]

重建路径:

S ← empty sequence
u ← target
while prev[u] is defined:           // Construct the shortest path with a stack S
    insert u at the beginning of S  // Push the vertex onto the stack
    u ← prev[u]                     // Traverse from target to source
insert u at the beginning of S      // Push the source onto the stack

答案 1 :(得分:0)

使用dijkstra,每次向“访问集”添加节点时,都会设置节点“父”或“源”,即来自访问集的节点,通过该节点添加节点。一旦到达目标节点,就从那里开始并向后移动父母,直到你回到源头。

您可以从打印此序列开始,或者如果您正在寻找更直观的方法,您可以查看graphviz工具和库集。