算法导论-22.3-6 用栈实现DFS

自己写的一个:

#include <iostream>
#include
<stack>
using namespace std;

const int maxV = 100, white = 0, gray = 1, black = 2;
int v, itime;
struct SNode{ //节点
int color, d, f, num;
SNode
*p;
};
struct SAdj{ //邻接表
int num;
SAdj
*next;
};
SAdj
*adj[maxV];
SNode
*vertex[maxV];
stack
<SNode*> vertexStack; //

//初始化
void ini(){
for(int i=1; i<=v; i++){
adj[i]
= new SAdj;
adj[i]
->next = NULL;
}
for(int i=1; i<=v; i++){
vertex[i]
= new SNode;
vertex[i]
->color = white;
vertex[i]
->p = NULL;
vertex[i]
->num = i;
}
itime
= 0;
}


void dfs(){
SNode
*top;

for(int i=1; i<=v; i++){ //书上的 DFS(G) 部分 (以实现DFS的“多个源顶点”)
if(vertex[i]->color == white){
vertex[i]
->color = gray;
vertex[i]
->d = ++itime;
vertex[i]
->p = NULL;
vertexStack.push(vertex[i]);
//新的树根
}

while(!vertexStack.empty()){
top
= vertexStack.top();
SAdj
*cur = adj[top->num]; //当前节点的邻接表
while(cur->next != NULL){
if(vertex[cur->next->num]->color == white){
vertex[cur
->next->num]->color = gray;
vertex[cur
->next->num]->d = ++itime;
vertex[i]
->p = top;

vertexStack.push(vertex[cur
->next->num]);
top
= vertexStack.top();
cur
= adj[cur->next->num];
}
else
cur
= cur->next;
}
top
->f = ++itime; //该节点已完成
top->color = black;
vertexStack.pop();
}
}

}

void print(){
for(int i=1; i<=v; i++){
cout
<< i << " " << vertex[i]->d << " " << vertex[i]->f << endl;
}
}

int main(){
cin
>> v;

ini();
int tmpU, tmpV;
while(true){
cin
>> tmpU >> tmpV;
if(tmpU == 0) break;

SAdj
*newNode = new SAdj;
newNode
->num = tmpV;
newNode
->next = adj[tmpU]->next;
adj[tmpU]
->next = newNode;
}

dfs();
print();

return 0;
}

————————————

测试数据:

6
1 4
1 2
2 5
3 6
3 5
4 2
5 4
6 6
0 0

(书 P331)

【另】,参考答案:

DFS(G) //Same as in text
for each vertex u in V
color[u]
= white
pi[u]
= nil
time
= 0
for each vertex u in V
if color[u] = white
DFS
-Visit(u)

DFS
-Visit(u)
color[u]
= gray
time
++
d[u]
= time
push(u)

while stack not empty
u
= top()
isleaf
= true
for each v in Adj[u]
if color[v] = white //found new node
color[v] = grey
pi[v]
= u
time
++
d[v]
= time
push(v)
isleaf
= false
break

if isleaf = true //u had no more white neighbors
color[u] = black
time
++
f[u]
= time
pop()
//remove u from stack

    原文作者:DFS
    原文地址: https://www.cnblogs.com/longdouhzt/archive/2011/08/05/2128996.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞