-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
64 lines (48 loc) · 1.09 KB
/
dfs.cpp
File metadata and controls
64 lines (48 loc) · 1.09 KB
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
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<int> *adj;
void dfs_util(int v, bool visited[]);
public:
Graph(int v);
void add_edge(int v, int w);
void dfs(int v);
};
Graph::Graph(int v){
this->V = v;
adj = new list<int>[v];
}
void Graph::add_edge(int v, int w){
adj[v].push_back(w);
}
void Graph::dfs_util(int v, bool visited[]){
visited[v] = true;
cout << v << " ";
list<int>::iterator _i;
for (_i = adj[v].begin() ; _i != adj[v].end(); _i++){
if(!visited[*_i]){
dfs_util(*_i, visited);
}
}
}
void Graph::dfs(int v){
bool *visited = new bool[v];
memset(visited, false, sizeof visited);
dfs_util(v, visited);
}
int main(){
std::ios_base::sync_with_stdio(false);
Graph g(4);
g.add_edge(0, 1);
g.add_edge(0, 2);
g.add_edge(1, 2);
g.add_edge(2, 0);
g.add_edge(2, 3);
g.add_edge(3, 3);
cout << "Following is Depth First Traversal"
" (starting from vertex 2) \n";
g.dfs(2);
cout << "\n";
return 0;
}