The traversal of graphs is divided into BFS width-first traversal and DFS depth-first traversal, the former takes the queue as the carrier and the latter with recursion as the carrier.
adjacency Table Template:
BFS
1#include <queue>2#include <iostream>3#include <cstdio>4#include <cstring>5 using namespacestd;6 Const intMAXN =100000+Ten;7queue<int>Q;8 intN, M, S, T, MS =0, Fch[maxn], ans =0;9 BOOLVIS[MAXN];Ten structtedge{ One intto, next; A }ADJ[MAXN]; - voidReadint&x) { -x =0;intsig =1;CharCH =GetChar (); the while(!isdigit (CH)) {if(ch = ='-') sig =-1; CH =GetChar ();} - while(IsDigit (CH)) {x =Ten* x + CH-'0'; CH =GetChar ();} -X *= sig;return ; - } + voidAddedge (intUintv) { -Adj[ms].next =Fch[u]; +Adj[ms].to =v; AFch[u] = ms + +; at return ; - } - voidBFS () { -Q.push (S); Vis[s] =true; Ans + +; - while(!Q.empty ()) { - intx =Q.front (); Q.pop (); in for(inti = fch[x]; I! =-1; i =Adj[i].next) { - intv =adj[i].to; to if(!Vis[v]) { +VIS[V] =true; - Q.push (v); theAns + +; * } $ }Panax Notoginseng } - return ; the } + voidinit () { Amemset (FCH,-1,sizeof(FCH)); the intu, v; + read (n); read (m); - for(inti =0; I < m; i + +){ $ read (u); Read (v); $ Addedge (U, v); - } -S =1; T =N; the return ; - }Wuyi voidprint () { theprintf"%d\n", ans); - return ; Wu } - intMain () { About init (); $ BFS (); - print (); - return 0; -}
Dfs
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;Const intMAXN =100000+Ten;intN, M, S, T, MS =0, Fch[maxn], ans =0;BOOLVIS[MAXN];structtedge{intto, next;} ADJ[MAXN];voidReadint&x) {x=0;intsig =1;CharCH =GetChar (); while(!isdigit (CH)) {if(ch = ='-') sig =-1; CH =GetChar ();} while(IsDigit (CH)) {x =Ten* x + CH-'0'; CH =GetChar ();} X*= Sig;return ;}voidAddedge (intUintv) {Adj[ms].next=Fch[u]; Adj[ms].to=v; Fch[u]= ms + +; return ;}voidDFS (intx) { if(Vis[x])return ; Ans++; VIS[X] =true; for(inti = fch[x]; I! =-1; i =Adj[i].next) DFS (adj[i].to); return ;}voidinit () {memset (FCH,-1,sizeof(FCH)); intu, v; Read (n); Read (m); for(inti =0; I < m; i + +) {read (u); Read (v); Addedge (U, v); } S=1; T =N; return ;}voidprint () {printf ("%d\n", ans); return ;}intMain () {init (); DFS (S); Print (); return 0;}
The traversal of graphs