C++ 邻接列表上的BFS和DFS

C++ 邻接列表上的BFS和DFS,c++,depth-first-search,breadth-first-search,adjacency-list,C++,Depth First Search,Breadth First Search,Adjacency List,所以我知道图形的广度优先搜索和深度优先搜索的基础知识,但我似乎不知道如何在邻接列表上执行这两种搜索。每次搜索从0开始 0->5->2->1->6 1->7->0 2->7->0 3->5->4 4->6->5->7->3 5->0->4->3 6->4->0 7->1->2->0->4 我不知道从哪里开始。我需要了解这一点,所以如果你能解释一下,那就太好了 邻接列表告诉您可以在每个节点的1跳内到达哪些节点。在您的示例中,节点0可以到达节点5、节点2、节点1和节点6 我将只解释BFS的情况,因为一

所以我知道图形的广度优先搜索和深度优先搜索的基础知识,但我似乎不知道如何在邻接列表上执行这两种搜索。每次搜索从0开始

0->5->2->1->6

1->7->0

2->7->0

3->5->4

4->6->5->7->3

5->0->4->3

6->4->0

7->1->2->0->4


我不知道从哪里开始。我需要了解这一点,所以如果你能解释一下,那就太好了

邻接列表告诉您可以在每个节点的1跳内到达哪些节点。在您的示例中,节点0可以到达节点5、节点2、节点1和节点6

我将只解释BFS的情况,因为一旦你得到它,你可能不会对DFS的情况有任何问题

在BFS中,伪代码如下所示:

Let graph be your adjacency list.
bool visited[num_nodes]; // Array of booleans to keep track if a node was visited.
for (int i = 0; i < num_nodes; i++)  // Set status of all nodes to be not visited.
  visited[i] = false;
start_node = 0; // E.g. start BFS at node 0.
visited[start_node] = true;
queue = Queue(); // Queue for keeping track of which node to check next
queue.append(start_node);
while (!queue.empty()) // While there is still nodes to check
{
 node = queue.pop_front(); // Get the node at the front of the queue.
 // For each of the neighbor of this node
 // This is where we make use of the adjacency list which tells us which nodes are the neighbors
 // of some other nodes.
 neighbors_of_node = graph[node];
 for (int i = 0; i < neighbors_of_node.size(); i++)
 {
  neighbor = neighbors_of_node[i];
  if (!visited[neighbor]) // If this node was not visited previously
  {
   do_something_with(neighbor);
   visited[neighbor] = true; // Indicate that we have visited this neighbor node.
   queue.append(neighbor);
  }
 }
}
让图形成为您的邻接列表。
bool访问了[num_节点];//用于跟踪节点是否被访问的布尔数组。
for(int i=0;i

上面的代码将访问从起始节点可以访问的所有节点。现在,如果图形不是完全连接的组件,会发生什么?如果要求访问所有节点,则需要从BFS末尾的一个剩余节点开始重复执行BFS。如何选择订单取决于您的问题。这将是您需要考虑的问题。

您需要某种方法避免返回到您已经访问过的节点,因为这将导致无限循环。您是否考虑过如何存储邻接?尝试对您更熟悉的图形(矩阵、对象)的表示执行BFS和DFS,然后在相邻列表上执行它们应该更容易。