BFS, breadth First search, one layer to traverse the diagram, it is called breadth first. Implementation method: Queue.
DFS, Depth-first search, wall-to-back traversal, called depth first. Implementation method: Recursive (Stack).
Both of these traversal methods are the basic way to access the graph. If the comparison of the tree, BFS corresponding to the level of traversal, DFS corresponding to three basic traversal methods (first order, middle order, post); The traversal tree starts with only one root, and the diagram needs to be a starting point for each of the points that have not been traversed to traverse the complete.
There's nothing to say, just look at the code.
Title Description: Enter a graph, the first row n, m for n points, M edge, the following m line input u, V for each line is a one-way edge (U,V); the DFS and BFS sequence of the output graph:
Input mode: File "Map1.in"
Output mode: Screen
Code:
#include <iostream>#include<cstdio>using namespacestd;Const intMAXN =10000;intN,m,start,end;structedge{intv; Edge*Next; Edge (int_v=0) {v=_v;}}*E[MAXN];voidAddedge (intUintv) {Edge*p=NewEdge (v); P->next=e[u]; e[u]=p;}voidinput () {CIN>>N>>M>>Start>>End; for(intI=1; i<=n;++i) e[i]=0; intu,v; for(intI=1; i<=m;++i) {cin>>u>>v; Addedge (U,V); }}BOOLMARK[MAXN];voidDFS (intu) { if(Mark[u])return; cout<<u<<" "; mark[u]=true; for(Edge *p=e[u];p;p=p->next) { intV=p->v; DFS (v); }}classqueue{intq[maxn],i,j; Public: Queue () {i=j=0; } voidClear () {i=j=0; } void inch(intu) {q[j++]=u;} int out() {returnq[i++]; } BOOLEmpty () {returni==J;} intSize () {returnJ-i;}}; Queue Q;voidBFS (intu) {q.clear (); Q.inch(u); mark[u]=true; while(!Q.empty ()) {u=q. out(); cout<<u<<" "; for(Edge *p=e[u];p;p=p->next) { intV=p->v; if(mark[v]==false) {Q.inch(v); mark[v]=true; } } }}intMain () {Freopen ("map1.in","R", stdin); Input (); for(intI=1; i<=n;++i) mark[i]=false; for(intI=1; i<=n;++i) DFS (i); cout<<Endl; for(intI=1; i<=n;++i) mark[i]=false; for(intI=1; i<=n;++i)if(mark[i]==false) BFS (i); cout<<Endl; Fclose (stdin); return 0;}
"Data Structure" C + + code BFS and DFS