I am trying to understand what is the space complexity of DFS and BFS in a graph.
I understand that the space complexity of BFS while using adjacency matrix would be O(v^2)
where v
is the number of vertices.
By using the adjacency list space complexity would be decreased in average case i.e < v^2
. But in the worst case, it would be O(v^2)
.
Even including Queue, it would be O(n^2)
(neglecting the lower value)
But, what is the scenario with DFS? Even if we use the adjacency matrix/list. Space Complexity would be O(v^2). But that seems to be a very loose bound, that too without considering stack frames.
Am I correct, regarding the complexities? If, not what are the space complexities of BFS/DFS? and while calculating Space Complexity for DFS, do we consider stack frame or not?
what is the tight bound of space complexity, for BFS and DFS for graph
答案 0 :(得分:1)
如伪代码1所示,邻接矩阵或邻接列表的空间消耗不在BFS算法中。邻接矩阵或邻接表是BFS算法的输入,因此不能包含在空间复杂度的计算中。 DFS也是如此。
伪代码1 输入:图Graph和图的起始顶点根
输出:目标状态。父链接将最短路径追溯到根
procedure BFS(G,start_v):
let Q be a queue
label start_v as discovered
Q.enqueue(start_v)
while Q is not empty
v = Q.dequeue()
if v is the goal:
return v
for all edges from v to w in G.adjacentEdges(v) do
if w is not labeled as discovered:
label w as discovered
w.parent = v
Q.enqueue(w)
BFS的空间复杂度可以表示为O(| V |),其中| V |是一组顶点的基数。对于最坏的情况,您需要将所有顶点都保留在队列中。
DFS的空间复杂度取决于实现方式。下面显示了具有最坏情况空间复杂度O(| E |)的DFS的非递归实现,其中E是边缘集的基数:
procedure DFS-iterative(G,v):
let S be a stack
S.push(v)
while S is not empty
v = S.pop()
if v is not labeled as discovered:
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
S.push(w)
深度优先搜索已完成,而深度优先搜索未完成。