深入理解深度优先搜索

    技术2025-11-09  10

         递归版本的伪代码如下:

    DFS(G) for each vertex u ∈ V [G] do color[u] ← WHITE π[u] ← NIL time ← 0 for each vertex u ∈ V [G] do if color[u] = WHITE then DFS-VISIT(u) DFS-VISIT(u) color[u] ← GRAY time ← time +1 d[u] ← time for each v ∈ Adj[u] do if color[v] = WHITE then π[v] ← u DFS-VISIT(v) color[u] BLACK time ← time +1 f [u] ← time

     

    非递归版本的C++ STL代码如下:

    const int TREE_SIZE = 9; std::stack<node*> visited, unvisited; node nodes[TREE_SIZE]; node* current; for( int i=0; i<TREE_SIZE; i++) //初始化树 { nodes[i].self = i; int child = i*2+1; if( child<TREE_SIZE ) //Left child nodes[i].left = &nodes[child]; else nodes[i].left = NULL; child++; if( child<TREE_SIZE ) //Right child nodes[i].right = &nodes[child]; else nodes[i].right = NULL; } unvisited.push(&nodes[0]); //先把0放入UNVISITED stack while(!unvisited.empty()) //只有UNVISITED不空 { current=(unvisited.top()); //当前应该访问的 unvisited.pop(); if(current->right!=NULL) unvisited.push(current->right); // 把右边压入 因为右边的访问次序是在左边之后 if(current->left!=NULL) unvisited.push(current->left); visited.push(current); cout<<current->self<<endl; }

     

    执行过程参考:

    http://www.comp.nus.edu.sg/~xujia/mirror/algorithm.myrice.com/algorithm/commonalg/graph/traversal/dfs.htm

     

    深度优先搜索设置3种状态的含义:WHITE:未访问;GRAY:已访问,但其后继结点还未访问完;Black:已访问,且其后继结点已全部访问完。3种状态在深度优先搜索中是必须的,各有其作用。

    除了创建一个深度优先森林外,深度优先搜索同时为每个结点加盖时间戳。每个结点v有两个时间戳:当结点v第一次被发现(并置成灰色)时记录下第一个时间戳d[v],当结束检查v的邻接表时(并置v为黑色)记录下第二个时间截f[v]。许多图的算法中都用到时间戳,他们对推算深度优先搜索进行情况是很有帮助的。

    最新回复(0)