邻接列表中的BFS和DFS

时间:2013-05-07 04:05:50

标签: 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 :(得分:9)

邻接列表告诉您每个节点可以在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);
  }
 }
}

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