-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs_recursive.cpp
More file actions
51 lines (43 loc) · 1.19 KB
/
dfs_recursive.cpp
File metadata and controls
51 lines (43 loc) · 1.19 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
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
using vertex_t = int;
using adjacency_list_t = unordered_map<vertex_t, vector<vertex_t>>;
using weight_t = int;
class Graph {
public:
adjacency_list_t adjacencyList;
int size;
Graph(adjacency_list_t al, int s) : adjacencyList(al), size(s) {}
vector<vertex_t> neighbours(vertex_t vertex) { return adjacencyList[vertex]; }
};
void dfs_visit(Graph g, vertex_t vertex, unordered_set<vertex_t> &visited) {
visited.insert(vertex);
cout << vertex << '\n';
for (auto neighbour : g.neighbours(vertex)) {
if (visited.find(neighbour) == visited.end()) {
dfs_visit(g, neighbour, visited);
}
}
}
void dfs(Graph g) {
unordered_set<vertex_t> visited;
for (auto vertex : g.adjacencyList) {
if (visited.find(vertex.first) == visited.end()) {
dfs_visit(g, vertex.first, visited);
}
}
}
void dfs(Graph g, vertex_t vertex) {
unordered_set<vertex_t> visited;
dfs_visit(g, vertex, visited);
}
int main() {
adjacency_list_t adjacencyList{
{1, {2, 7, 8}}, {2, {3, 6}}, {3, {4, 5}}, {8, {9, 12}}, {9, {10, 11}}};
Graph g(adjacencyList, 12);
dfs(g);
return 0;
}