-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstDirectedPaths.h
More file actions
41 lines (37 loc) · 893 Bytes
/
DepthFirstDirectedPaths.h
File metadata and controls
41 lines (37 loc) · 893 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
#pragma once
#include <vector>
#include <algorithm>
class DepthFirstDirectedPaths
{
using Bag = std::vector<int>;
std::vector<bool> marked;
std::vector<int> edgeTo;
const int source;
public:
DepthFirstDirectedPaths(Digraph& G, int s)
: source(s), marked(G.V()), edgeTo(G.V())
{
dfs(G, s);
}
void dfs(Digraph& G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
}
}
bool hasPathTo(int v) {
return marked[v];
}
Bag pathTo(int v) {
if (!hasPathTo(v)) return Bag();
Bag stack;
for (int x = v; x != source; x = edgeTo[x])
stack.push_back(x);
stack.push_back(source);
std::reverse(stack.begin(), stack.end());
return stack;
}
};