簡體   English   中英

使用 Dijkstra 算法跟蹤兩個節點之間的最短路徑

[英]Keeping track of the shortest path between two nodes using Dijkstra's algorithm

我對 c++ 很陌生,並且在修改 Dijkstra 的算法以跟蹤兩個節點之間的最短路徑時遇到了麻煩,而不僅僅是最短距離。 我讓它正確計算最短距離。 這是計算最短距離的 function:

  vector<vertex<T>> shortest_path(directed_graph<T> g, int u_id, int v_id) {
  vector<vertex<T>> shortest;
  vector<vector<T>> graph = g.get_adjacency_matrix();

  if (!g.contains(u_id) && !g.contains(v_id)) {
    return shortest;
  }

  shortest.push_back(vertex<T>(u_id, g.get_vert_weight(u_id)));

  int *dist = new int[g.num_vertices()]; // Will hold the shortest distance from u_id to i
  bool *sptSet = new bool[g.num_vertices()]; // Will be true if vertex i is including in shortest path tree from u_id to i

  int parent[g.num_vertices()]; // parent to store the shortest path tree

  // initialise all distances as INFINITE and set stpset as false
  for (int i = 0; i < g.num_vertices(); i++) {
    parent[u_id] = -1;
    dist[i] = INT_MAX;
    sptSet[i] = false;
  }

  dist[u_id] = 0; // Distance of source vertex to itself is always 0

  for (int count = 0; count < (g.num_vertices() - 1); count++) { // find shortest path for all vertices
    int u = min_distance(dist, sptSet, g.num_vertices()); // pick the min distance vertex from the set of vertices not yet processed
    sptSet[u] = true; // mark the picked vertex as processed

    for (int v = 0; v < g.num_vertices(); v++) { // update dist value of the adjacent vertices of the picked vertex
      // update dist[v] only if its not in sptset, there is an edge from u to v, and total weight of path from u_id to v
      // through u is smaller than current distance value of dist[v]
      if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
        parent[v] = u;
        dist[v] = dist[u] + graph[u][v];
      }
    }
  }

  for (int i = 0; i < g.num_vertices(); i++) {
    if (dist[i] != INT_MAX) {
      cout << u_id << " -> " << i << " : " << dist[i] << endl;
    } else {
      cout << u_id << " -> " << i << " : n/a" << endl;
    }
  }

  return shortest;

}

這是我用來測試的圖表:

    g1.add_edge(0, 1, 4);
    g1.add_edge(7, 0, 8);
    g1.add_edge(1, 7, 11);
    g1.add_edge(7, 8, 7);
    g1.add_edge(1, 2, 8);
    g1.add_edge(8, 2, 2);
    g1.add_edge(7, 6, 1);
    g1.add_edge(8, 6, 6);
    g1.add_edge(6, 5, 2);
    g1.add_edge(5, 2, 4);
    g1.add_edge(2, 3, 7);
    g1.add_edge(3, 5, 14);
    g1.add_edge(4, 3, 9);
    g1.add_edge(5, 4, 10);

有人可以幫我最短路徑嗎?

您可以利用parent數組來重建從目標節點到源節點的路徑,例如:

vector<int> path;
int idx = v_id;
while (idx != u_id) {
    path.emplace_back(idx);
    idx = parent[idx];
}
path.emplace_back(idx);
reverse(path.begin, path.end());
cout << "PATH: ";
for (int x : path) {
    cout << x << " ";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM