-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
50 lines (38 loc) · 797 Bytes
/
dfs.cpp
File metadata and controls
50 lines (38 loc) · 797 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
#include <iostream>
#include <vector>
using namespace std;
class Graph {
public:
int V;
vector<vector<int>> adjecency_list;
vector<bool> visited;
Graph(int v) {
V = v;
adjecency_list.resize(v);
visited.resize(v, false);
}
void add_edge(int u, int v) {
adjecency_list[u].push_back(v);
}
};
void dfs(Graph &g, int u) {
g.visited[u] = true;
cout << u << " ";
for(auto v : g.adjecency_list[u]) {
if(!g.visited[v])
dfs(g, v);
}
}
int main() {
int u;
cin >> u;
Graph g(6);
g.add_edge(0, 1);
g.add_edge(0, 2);
g.add_edge(1, 3);
g.add_edge(1, 4);
g.add_edge(2, 3);
g.add_edge(4, 5);
dfs(g, u);
return 0;
}