【发布时间】: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