Advertisement
Evirir

Untitled

Dec 23rd, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> adj[100];   //adjacency list (an array of vectors)
  5. bool visited[100];      //to keep track which vertices are visited
  6.  
  7. void DFS(int v){
  8.     //terminate function if vertex is visited
  9.     if(visited[v]==true)    return;
  10.    
  11.     visited[v]=true;    //mark as visited
  12.     cout<<v<<" ";       //prints out current vertex
  13.    
  14.     //for each vertex connected to current vertex, do DFS (recursive function)
  15.     for(int i=0;i<adj[v].size();i++){
  16.         int x=adj[v][i];
  17.         if(!visited[x]) DFS(x);
  18.     }
  19. }
  20.  
  21. int main()
  22. {
  23.     int V,E; //specify no of vertices,V and edges,E
  24.     cin>>V>>E;
  25.    
  26.     //create adjacency list (input E pairs of vertices that are connected by an edge)
  27.     for(int i=0;i<E;i++){
  28.         int a,b;
  29.         cin>>a>>b;
  30.         adj[a].push_back(b);
  31.         adj[b].push_back(a);
  32.     }
  33.    
  34.     DFS(0); //start DFS from vertex 0
  35.    
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement