Depth first search(DFS) of the graph in c++.

  We are going to implement the Depth first search    by using c++.

Code:-

#include<bits/stdc++.h>
using namespace std;
vector<int> arr[100] ;
int visited[100];

// function definition of dfs
void dfs(int n)
{
visited[n]=1;
cout<<n<<” “;
for(int child: arr[n])
{
if(visited[child]==0)
dfs(child);
}
}

//Driver program
int main()
{
int v,e;
cout<<“Enter number of vertex and edgesn”;
cin>>v>>e;
int a,b;
cout<<“Enter all the vertex like a and bn”;
for(int i=0;i<e;i++)
{
cin>>a>>b;
arr[a].push_back(b);
arr[b].push_back(a);
}
//function calling
dfs(1);
return 0;
}

Output:- 

Enter number of vertex and edges
6 5
Enter all the vertex like a and b
1 2
2 3
3 4
4 5
4 6

1 2 3 4 5 6



Leave a Reply

Your email address will not be published.