Guest User

DFS/BFS

a guest
Jun 16th, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std ;
  5.  
  6. vector<int> g[100010] ;
  7. bool vis[100010] ;
  8.  
  9. void dfs(int x) {
  10.     cout << x << ' ' ;
  11.     vis[x] = true ;
  12.     for(auto i:g[x])
  13.         if(!vis[i])
  14.             dfs(i) ;
  15. }
  16.  
  17. void bfs() {
  18.     queue<int> qu ;
  19.     vis[1] = true ;
  20.     qu.push(1) ;
  21.  
  22.     while(!qu.empty()) {
  23.         int u = qu.front() ;
  24.         qu.pop() ;
  25.         cout << u << ' ' ;
  26.  
  27.         for(auto i:g[u]) {
  28.             if(!vis[i]) {
  29.                 vis[i] = true ;
  30.                 qu.push(i) ;
  31.             }
  32.         }
  33.     }
  34. }
  35.  
  36. int main() {
  37.     int n, m ;
  38.  
  39.     cin >> n >> m ;
  40.     for (int i=0; i<m; ++i) {
  41.         int a, b ;
  42.         cin >> a >> b ;
  43.         g[a].push_back(b) ;
  44.         g[b].push_back(a) ;
  45.     }
  46.  
  47.     for (int i=1; i<=n; ++i) vis[i] = false ;
  48.     dfs(1) ;
  49.     cout << endl ;
  50.  
  51.     for (int i=1; i<=n; ++i) vis[i] = false ;
  52.     bfs() ;
  53.     cout << endl ;
  54. }
  55.  
  56. /*
  57.  
  58. 5 6
  59. 1 2
  60. 1 4
  61. 2 3
  62. 2 4
  63. 2 5
  64. 4 5
  65.  
  66. */
Advertisement
Add Comment
Please, Sign In to add comment