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 edges\n";
cin>>v>>e;
int a,b;
cout<<"Enter all the vertex like a and b\n";
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
0 Comments