深度优先搜索 (DFS) 与广度优先搜索 (BFS) 伪代码和复杂度

时间:2021-05-14 02:57:30

标签: algorithm time-complexity depth-first-search breadth-first-search pseudocode

我必须为计算连接数的算法开发伪代码 图中的分量 G = (V, E) 给定顶点 V 和边 E。

我知道我可以使用深度优先搜索或广度优先搜索来计算连通分量的数量。

然而,我想用最高效的算法来解决这个问题,但我不确定每个算法的复杂度。

下面尝试以伪代码形式编写 DFS。

function DFS((V,E))
     mark each node in V with 0
     count ← 0
     for each vertex in V do
          if vertex is marked then
               DFSExplore(vertex)

function DFSExplore(vertex)
     count ← count + 1
     mark vertex with count
     for each edge (vertex, neighbour) do
          if neighbour is marked with 0 then
               DFSExplore(neighbour)

下面尝试以伪代码形式编写 BFS。

function BFS((V, E))
     mark each node in V with 0
     count ← 0, init(queue)     #create empty queue 
     for each vertex in V do
          if vertex is marked 0 then
               count ← count + 1
               mark vertex with count
               inject(queue, vertex)             #queue containing just vertex
               while queue is non-empty do
                    u ← eject(queue)                          #dequeues u
                    for each edge (u, w) adjacent to u do
                         if w is marked with 0 then
                              count ← count + 1
                              mark w with count
                              inject(queue, w)     #enqueues w

我的讲师说 BFS 与 DFS 具有相同的复杂性。

然而,当我向上搜索深度优先搜索的复杂度时,它是 O(V^2),而当使用邻接表时,广度优先搜索的复杂度是 O(V + E) 和 O(V^ 2) 当使用邻接矩阵时。

我想知道如何计算 DFS / BFS 的复杂度,我想知道如何调整伪代码来解决问题。

1 个答案:

答案 0 :(得分:2)

如果您使用邻接表,DFS 和 BFS 的时间复杂度相同,即 O(V+E)。因此,如果您问哪个更好,那么这完全取决于您要解决的问题类型。假设你想解决一个问题,你的目标靠近起始顶点,那么 BFS 将是更好的选择。另外,如果您考虑内存,那么 DFS 是更好的选择,因为不需要存储子指针。

enter image description here

图片提供 - Narasimha karumanchi 的 DSA Made Easy

相关问题