如何在不违反O(| V | + | E |)的情况下在dfs树中存储节点级别

时间:2016-11-02 16:32:52

标签: algorithm graph depth-first-search

有没有办法在它所属的DFS树中存储每个顶点的级别?

时间复杂度应为O(|V| + |E|)

1 个答案:

答案 0 :(得分:0)

这是来自wikipedia的标准DFS伪代码:

1  procedure DFS(G,v):
2      label v as discovered
3      for all edges from v to w in G.adjacentEdges(v) do
4          if vertex w is not labeled as discovered then
5              recursively call DFS(G,w)

添加级别:

1  procedure DFS(G,v,level):
2      label v as discovered
3      v.level = level
4      for all edges from v to w in G.adjacentEdges(v) do
5          if vertex w is not labeled as discovered then
6              recursively call DFS(G,w,level+1)

首先致电DFS(G,v,0)