标签:
图的遍历分为BFS宽度优先遍历和DFS深度优先遍历两种,前者以队列为载体,后者以递归为载体。
邻接表模板:
BFS
1 #include <queue> 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 const int maxn = 100000 + 10; 7 queue<int> Q; 8 int n, m, S, T, ms = 0, fch[maxn], ans = 0; 9 bool vis[maxn]; 10 struct Tedge{ 11 int to, next; 12 }adj[maxn]; 13 void read(int &x){ 14 x = 0; int sig = 1; char ch = getchar(); 15 while(!isdigit(ch)) { if(ch == ‘-‘) sig = -1; ch = getchar(); } 16 while(isdigit(ch)) { x = 10 * x + ch - ‘0‘; ch = getchar(); } 17 x *= sig; return ; 18 } 19 void AddEdge(int u, int v){ 20 adj[ms].next = fch[u]; 21 adj[ms].to = v; 22 fch[u] = ms ++; 23 return ; 24 } 25 void BFS(){ 26 Q.push(S); vis[S] = true; ans ++; 27 while(!Q.empty()){ 28 int x = Q.front(); Q.pop(); 29 for(int i = fch[x]; i != -1; i = adj[i].next){ 30 int v = adj[i].to; 31 if(!vis[v]){ 32 vis[v] = true; 33 Q.push(v); 34 ans ++; 35 } 36 } 37 } 38 return ; 39 } 40 void init(){ 41 memset(fch, -1, sizeof(fch)); 42 int u, v; 43 read(n); read(m); 44 for(int i = 0; i < m; i ++){ 45 read(u); read(v); 46 AddEdge(u, v); 47 } 48 S = 1; T = n; 49 return ; 50 } 51 void print(){ 52 printf("%d\n", ans); 53 return ; 54 } 55 int main(){ 56 init(); 57 BFS(); 58 print(); 59 return 0; 60 }
DFS
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxn = 100000 + 10; int n, m, S, T, ms = 0, fch[maxn], ans = 0; bool vis[maxn]; struct Tedge{ int to, next; }adj[maxn]; void read(int &x){ x = 0; int sig = 1; char ch = getchar(); while(!isdigit(ch)) { if(ch == ‘-‘) sig = -1; ch = getchar(); } while(isdigit(ch)) { x = 10 * x + ch - ‘0‘; ch = getchar(); } x *= sig; return ; } void AddEdge(int u, int v){ adj[ms].next = fch[u]; adj[ms].to = v; fch[u] = ms ++; return ; } void DFS(int x){ if(vis[x]) return ; ans ++; vis[x] = true; for(int i = fch[x]; i != -1; i = adj[i].next) DFS(adj[i].to); return ; } void init(){ memset(fch, -1, sizeof(fch)); int u, v; read(n); read(m); for(int i = 0; i < m; i ++){ read(u); read(v); AddEdge(u, v); } S = 1; T = n; return ; } void print(){ printf("%d\n", ans); return ; } int main(){ init(); DFS(S); print(); return 0; }
标签:
原文地址:http://www.cnblogs.com/chxer/p/4392451.html