《算法导论》DFS求路径算法

转自于http://www.cnblogs.com/longdouhzt/archive/2011/08/05/2128996.html



#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 init(){
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++){
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->F3_120M_512=++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;
init();
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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值