Fastrail08

DFS

Aug 4th, 2025
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void dfs(int source, vector<bool> &visited, vector<vector<int> > &adj){
  5.    
  6.     //level = source
  7.     //options = neighbours of source
  8.    
  9.     //mark source visited
  10.     visited[source] = true;
  11.     cout << source << " ";
  12.     for(int i = 0; i < adj[source].size(); i++){
  13.         int node = adj[source][i];
  14.         if(!visited[node]){
  15.             dfs(node, visited, adj);
  16.         }
  17.     }
  18.    
  19. }
  20.  
  21. int main() {
  22.     // your code goes here
  23.     int n, m;
  24.     cin >> n >> m;
  25.    
  26.     vector<vector<int> > adj(n + 1, vector<int>());
  27.    
  28.     for(int i = 0; i < n; i++){
  29.         int u, v;
  30.         cin >> u >> v;
  31.         adj[u].push_back(v);
  32.         adj[v].push_back(u);
  33.     }
  34.     vector<bool> visited(n + 1, false);
  35.     int source = 1;
  36.     dfs(source, visited, adj);
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment