- BFS:
- 思路:首先遍历所有相邻的顶点
- BFS就像是在湖面上扔一块石头,然后观察波纹一圈圈地扩散开来。也就是说,我们首先访问起始节点的所有邻居,然后再访问这些邻居的所有邻居,以此类推。
- 在代码中,BFS的实现基于队列。
- 首先,我们将起始节点放入队列并标记为已访问(黑色)。然后,只要队列不为空,我们就从队列中取出一个节点,访问它的所有未访问(白色)的邻居,将这些邻居节点加入队列并标记为已访问。
- 代码如图
- Time Complexity
- When a node u is dequeued,
- ◦ We examine all of its neighbors (check their color), enqueue them and color them to gray if they are white
- ◦ After that, we color u as black
- ◦ This incurs c(1 + d-out(u) ) costs for node u where c is a constant (if we use an adjacency list to represent the graph)
- Each node is dequeued at most once
- Therefore, the total running time with adjacency list representation is
- When a node u is dequeued,
- 思路:首先遍历所有相邻的顶点
- DFS:
- 思路:首先遍历一条分支上最深的顶点
- 想象你正在探索一座深深的洞穴。你带着一盏手电筒,决定一直向前走,直到找到宝藏或者无路可走。当你无路可走的时候,你会回到最近的一个岔路口,然后选择另一条路继续前进。这就是深度优先搜索的基本思想。
- 在代码中,DFS的实现基于递归。
- 首先,我们选择一个起始节点,标记它为已访问(黑色)。然后,我们查找这个节点的所有未访问(白色)的邻居节点,并对每个邻居节点进行DFS,即将它当作新的起始节点。如果所有的邻居节点都已经被访问(黑色),则返回。
- 代码如图:
- 注:布尔数组(Boolean array)在Java中刚被创建时,默认情况下的元素值是False。
- Time Complexity
- When a node v gets popped from the stack?
- ◦ None of its out-neighbors is a white node
- ◦ We may need to repeatedly check if node v has white out-neighbor
- As each node is popped at most once, DFS’s time cost is
- When a node v gets popped from the stack?
- Properties of DFS
- 思路:首先遍历一条分支上最深的顶点
[DS:10.2-3]Introduction of BFS and DFS
最新推荐文章于 2024-05-17 12:22:02 发布