-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtraversal.h
67 lines (48 loc) · 1.27 KB
/
traversal.h
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
65
66
67
#ifndef GRAPH_TRAVERSAL_H_
#define GRAPH_TRAVERSAL_H_
#include <queue>
#include <stack>
#include "graph/types.h"
// T~O(N+E), S~O(N)
inline vector<int> bfsTraversal(const AdjacencyList& graph, const int start) {
if (graph.empty()) { return {}; }
vector<int> order;
order.reserve(graph.size());
queue<int> open;
open.push(start);
vector<bool> closed(graph.size(), false);
closed[start] = true;
while (!open.empty()) {
const int current = open.front();
open.pop();
order.push_back(current);
for (const int child : graph.at(current)) {
if (closed[child]) { continue; }
open.push(child);
closed[child] = true;
}
}
return order;
}
// T~O(N+E), S~O(N)
inline vector<int> dfsTraversal(const AdjacencyList& graph, const int start) {
if (graph.empty()) { return {}; }
vector<int> order;
order.reserve(graph.size());
stack<int> open;
open.push(start);
vector<bool> closed(graph.size(), false);
closed[start] = true;
while (!open.empty()) {
const int current = open.top();
open.pop();
order.push_back(current);
for (const int child : graph.at(current)) {
if (closed[child]) { continue; }
open.push(child);
closed[child] = true;
}
}
return order;
}
#endif // GRAPH_TRAVERSAL_H_