图的搜索

dfs nonrecursion
 1 int _visited[50];
2 void DFS_Norecursion(const Graph* g)
3 {
4 for(int i=0;i<g->v;++i)
5 {
6 _visited[i]=0;
7 p_dfs[i]=0;
8 }
9 int pp=0;
10 for(int i=0;i<g->v;++i)
11 {
12 int m=i;
13 while(!s.empty() || _visited[m]==0)
14 {
15 if(_visited[m]==0)
16 {
17 cout <<"Visit Vertex "<<m+1<<" ";
18 _visited[m]=1;
19 p_dfs[m]=pp;
20 time++;
21 start_dfs[m]=time;
22 s.push(g->vertices[m]);
23 Edge* tmp=g->vertices[m].head;
24 while(tmp!=NULL)
25 {
26 s.push(g->vertices[tmp->adj_vertex-1]);
27 tmp=tmp->next;
28 }
29 }
30 else if(_visited[m]==1)
31 {
32 _visited[m]=2;
33 finish_dfs[m]=time;
34 time++;
35 }
36 Vertex vtx=s.top();
37 s.pop();
38 pp=m;
39 m=vtx.vertex-1;
40 }
41 }
42 }

 

graph
 1 //Graph stored as an adjacency list
2 typedef struct Edge
3 {
4 int adj_vertex;
5 int weight;
6 struct Edge* next;
7 }Edge;
8
9 typedef struct Vertex
10 {
11 int vertex;
12 Edge* head;
13 }Vertex;
14
15 struct Graph
16 {
17 Vertex vertices[50];
18 int v;//number of vertices
19 int e;//number of edges
20 };

 

bfs
 1 //breadth first search, just one source vertex
2 void BFS(const Graph* g)
3 {
4 bool visited[50];//if vertex visited
5 int dist[50];//shortest distance from source to each vertex
6 int p[50];//parent in BFS tree
7 queue<Vertex> q;
8 visited[0]=true;//mark vertex 1 as source
9 dist[0]=0;
10 p[0]=0;
11 for(int i=1;i<g->v;++i)
12 {
13 visited[i]=false;
14 dist[i]=999;//not reached
15 p[i]=0;
16 }
17 cout <<"visit vertex 1"<<" ";
18 q.push(g->vertices[0]);
19 while(!q.empty())
20 {
21 Vertex tmp=q.front();
22 q.pop();
23 Edge* link=tmp.head;
24 while(link!=NULL)
25 {
26 int order=link->adj_vertex;
27 if(visited[order-1]==false)
28 {
29 cout <<"visit vertex "<<order<<" ";
30 visited[order-1]=true;
31 dist[order-1]=dist[tmp.vertex-1]+1;
32 p[order-1]=tmp.vertex;
33 q.push(g->vertices[order-1]);
34 }
35 link=link->next;
36 }
37 }
38 }
dfs
 1 //This is for DFS
2 bool visited_dfs[50];
3 int start_dfs[50];
4 int finish_dfs[50];
5 int p_dfs[50];
6 int time=0;//time stamp
7 //
8
9 //DFS starts at every vertex, only when it is not visited
10 void DFS_Visit(Vertex v,const Graph* g)
11 {
12 cout <<"Visit Vertex "<<v.vertex<<" ";
13 visited_dfs[v.vertex-1]=true;
14 time++;
15 start_dfs[v.vertex-1]=time;
16 Edge* tmp=v.head;
17 while(tmp!=NULL)
18 {
19 if(visited_dfs[tmp->adj_vertex-1]==false)
20 {
21 p_dfs[tmp->adj_vertex-1]=v.vertex;
22 DFS_Visit(g->vertices[tmp->adj_vertex-1],g);
23 }
24 tmp=tmp->next;
25 }
26 finish_dfs[v.vertex-1]=time;
27 }
28
29 void DFS(const Graph* g)
30 {
31 for(int i=0;i<g->v;++i)
32 {
33 visited_dfs[i]=false;
34 p_dfs[i]=0;
35 }
36 for(int i=0;i<g->v;++i)
37 if(visited_dfs[i]==false)
38 DFS_Visit(g->vertices[i],g);
39 }
test
1 int main()
2 {
3 Graph* g=new Graph;
4 Create_Graph(g);
5 BFS(g);
6 cout <<endl;
7 DFS(g);
8 return 0;
9 }




posted @ 2012-02-21 10:14  Cavia  阅读(222)  评论(0编辑  收藏  举报