-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderDepthFirst.hh
More file actions
46 lines (40 loc) · 1.1 KB
/
OrderDepthFirst.hh
File metadata and controls
46 lines (40 loc) · 1.1 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
#pragma once
#include "Graph.hh"
struct DepthFirstOrder {
std::deque<bool> marked;
std::deque<int> preorder;
std::deque<int> postorder;
DepthFirstOrder(const Digraph &G)
: marked(G.V, false), preorder(), postorder() {
for (int v = 0; v < G.V; ++v)
if (!marked[v]) dfs(G, v);
}
void dfs(const Digraph &G, int v) {
preorder.push_back(v);
marked[v] = true;
for (int w : G.adj[v]) {
if (!marked[w]) dfs(G, w);
}
postorder.push_back(v);
}
DepthFirstOrder(const EdgeWeightedDigraph &G)
: marked(G.V, false), preorder(), postorder() {
for (int v = 0; v < G.V; ++v)
if (!marked[v]) dfs(G, v);
}
void dfs(const EdgeWeightedDigraph &G, int v) {
preorder.push_back(v);
marked[v] = true;
for (const auto &e : G.adj[v]) {
if (int w{e.to}; !marked[w]) dfs(G, w);
}
postorder.push_back(v);
}
std::deque<int> pre() const { return preorder; }
std::deque<int> post() const { return postorder; }
std::deque<int> reversePost() const {
std::deque<int> deck;
for (int v : postorder) deck.push_front(v);
return deck;
}
};