问题描述
我必须为计算连接数的算法开发伪代码 图中的分量 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 的复杂度,我想知道如何调整伪代码来解决问题。