【问题标题】:Printing shortest path from unweighted graph从未加权图打印最短路径
【发布时间】:2016-10-18 15:46:08
【问题描述】:

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

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 的最短路径,但我不知道如何有效地保存该路径然后打印它。知道如何解决吗?

【问题讨论】:

  • 你为什么不向我们展示你是如何实现 bfs 的,它会更容易帮助你弄清楚如何保存你的结果。
  • @xaxxon 更新 bfs
  • 我建议创建一个“来自”地图来存储您到达每个节点的方式。然后,当您达到目标时,只需使用该地图向后走。

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


【解决方案1】:

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

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

【讨论】:

  • addEdge(0, 1), addEdge(0, 2);这意味着 0 是 1 和 2 的源和父,所以 graph[0] 是指向名为 0 和 1 的 2 个节点的链表的指针>
  • @paxie 你已经访问了这个数组,你可以添加另一个数组,其中包含父元素。这里的parent是指你访问该节点的那个节点,所以基本上应该是visited[*i] = true; parent[*i]=s;
  • 使用另一个数据结构来存储父关系。一个数组a,例如a[1] = 0a[2]=0,那么你可以直接跳过数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多