c++ - 从未加权图中打印最短路径

标签 c++ algorithm graph breadth-first-search

我有一个表示为邻接表的有向图:

enter image description here

class Graph
{
    private:
        struct Node
        {
            Node *next;
            int vertex;
            Node( int vertex )
            {
                this -> vertex = vertex;
                this -> next = nullptr;
            }
        };

        Node ** graph;
        int V;

public:
    Graph(int size)
    {
        V = size;
        graph = new Node*[V];
        for ( int i = 0; i < V; i++ )
            graph[i] = nullptr;
    }

   // Add edge from Source to destination
   void addEdge( int source, int destination )  
   {
      Node * ref = graph[from];
      graph[from] = new Node( to );
      graph[from] -> next = ref;
   }

  void bfs ( int s, int dest )
  {
   // ...
  }

我已经实现了 bfs,它为我提供了从节点 A 到节点 B 的最短路径,但我不知道如何有效地保存该路径然后打印它。知道如何解决吗?

最佳答案

如果您从节点 A 开始执行 BFS,您访问的所有节点可能有多个子节点,但每个节点只有一个父节点。当您浏览图表时,只需保存您访问的每个节点的父节点(尚未访问)。

当您找到节点 B 时,只需查找其父节点,然后查找其父节点的父节点,依此类推。这为您提供了路径。

关于c++ - 从未加权图中打印最短路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40112666/

相关文章:

c++ - 在 C++ 中的自定义字符串类中实现插入?

c++ - 具有不同类的类函数的函数指针数组

java - 以最小成本(时间和空间)的图形表示

c++ - 向下转换 boost::polymorphic_pointer_downcast 或 boost::dynamic_pointer_cast 哪个更好用

c++ - 如何实现用于配置功能的通用 C++?

python - 编程挑战中的高耗时和低效率

algorithm - 图检查三个节点之间是否存在路径

java - 我的倒置计数算法有什么问题?

python - 根据连通性和坐标分离两个图

graph - Tinkerpop - 我如何在图中找到一个节点?