vaibhav1906

DFS Code

Jan 4th, 2022
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void addEdge(vector<int> adj[], int u, int v)
  5. {
  6.     adj[u].push_back(v);
  7. }
  8. void dfs(vector<int> adj[], int vertex, vector<int> & vis)
  9. {
  10.     vis[vertex]=1;
  11.     cout<<vertex<<" ";
  12.     for(int x:adj[vertex])
  13.     {
  14.         if(vis[x]==0)
  15.             dfs(adj,x,vis);
  16.     }
  17. }
  18.  
  19. void printGraph(vector<int> adj[], int V)
  20. {
  21.     for (int v = 0; v < V; ++v)
  22.     {
  23.         cout << "Adjacency list of vertex "
  24.              << v << "\n";
  25.         for (auto x : adj[v])
  26.            cout << x <<" ";
  27.         cout<<"\n";
  28.     }
  29. }
  30. int main()
  31. {
  32.     int V = 5;
  33.     vector<int> adj[V];
  34.     addEdge(adj,0, 1);
  35.     addEdge(adj,0, 2);
  36.     addEdge(adj,1, 2);
  37.     addEdge(adj,2, 0);
  38.     addEdge(adj,2, 3);
  39.     addEdge(adj,3, 3);
  40.     addEdge(adj,4, 4);
  41.     //printGraph(adj,V);
  42.     vector<int> vis(V,0);
  43.     for(int i=0;i<V;i++)
  44.     {
  45.         if(vis[i]==0)
  46.             dfs(adj,i,vis);
  47.     }
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment