forked from Sanchitbajaj02/CppPrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS_Traversal.cpp
60 lines (47 loc) · 858 Bytes
/
DFS_Traversal.cpp
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
56
57
58
59
60
//Depth First Search
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
class Graph{
int n;//number of nodes
list<int> *adj;//array of linked lists
public:
Graph(int n){
this->n=n;
adj=new list<int>[n];
}
void addEdge(int a,int b){
a--;b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
void dfs(int c,vector<bool> &visited){
visited[c]=1;
for(auto &x:adj[c]){
if(visited[x])continue;
dfs(x,visited);
}
cout << c+1 << endl;
}
void dfs(int c){
c--;
vector<bool> visited(n,0);
dfs(c,visited);
}
};
int main(){
cout << "Enter number of nodes" << endl;
int n;cin >> n;
Graph gr(n);
cout << "Enter number of edges" << endl;
int e;cin >> e;
cout << "Enter Edges" << endl;
for (int i = 0; i < e; ++i)
{
int a,b;
cin >> a >> b;
gr.addEdge(a,b);
}
gr.dfs(1);//dfs from 1
return 0;
}