Skip to content

Instantly share code, notes, and snippets.

@ravikiran0606
Created September 25, 2016 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravikiran0606/4c1dd0ecefbe868be89d13a2e32c924a to your computer and use it in GitHub Desktop.
Save ravikiran0606/4c1dd0ecefbe868be89d13a2e32c924a to your computer and use it in GitHub Desktop.
Graph Traversal : DFS (Depth First Search)
#include<bits/stdc++.h>
using namespace std;
vector< vector<int> >graph;
vector<bool>vis;
void dfsvisit(int s){
vis[s]=true;
cout<<s<<" ";
for(int i=0;i<graph[s].size();i++){
if(!vis[graph[s][i]]){
dfsvisit(graph[s][i]);
}
}
}
int main()
{
int n,i,t,j,a;
cout<<"Enter the no of vertices..";
cin>>n;
vis.resize(n+1);
graph.resize(n+1);
for(i=1;i<=n;i++){
cout<<"\nEnter the no of adjacent vertexes to the vertex "<<i<<endl;
cin>>t;
cout<<"\nEnter the vertices..";
for(j=1;j<=t;j++){
cin>>a;
graph[i].push_back(a);
}
}
// Doing DFS Search...( Using Recursion )
fill_n(vis.begin(),n+1,false);
cout<<"\nThe DFS Traversal done implicitly is ... ";
for(i=1;i<=n;i++){
if(!vis[i]){
dfsvisit(i);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment