-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
55 lines (42 loc) · 939 Bytes
/
dfs.cpp
File metadata and controls
55 lines (42 loc) · 939 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<vector>
using namespace std;
void dfs(std::vector<std::vector<int>> &);
void dfsHelper(int in, std::vector<std::vector<int>> &, bool *);
int main(){
int n ;
cout<<"Enter the number of nodes\n";
cin>>n;
std::vector<std::vector<int>> v(n);
// int * visited = new int[n];
cout<<"Enter the number of edges\n";
int e;
cin>>e;
for(int i = 0 ; i < e; i++){
int sv , ev;
cin>>sv>>ev;
v[sv].push_back(ev);
v[ev].push_back(sv);
}
dfs(v);
return 0;
}
void dfs(std::vector<std::vector<int>> &v){
bool * visited = new bool[v.size()];
for(int i = 0; i < v.size(); i++)
{
if(!visited[i])
dfsHelper(i,v,visited);
}
}
void dfsHelper( int in ,std::vector<std::vector<int>> &v , bool * visited ){
visited[in] = true;
cout<<in<<" ";
for(auto element : v[in]){
if(visited[element])
continue;
// cout<<element<<" ";
dfsHelper(element,v,visited);
}
return;
}