-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirected_cycle.cpp
More file actions
30 lines (28 loc) · 884 Bytes
/
Directed_cycle.cpp
File metadata and controls
30 lines (28 loc) · 884 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
#include "Directed_cycle.h"
Directed_cycle::Directed_cycle(const Digraph& digraph)
: _marked(digraph.num_vertices(), false),
_edge_to(digraph.num_vertices()),
_on_stack(digraph.num_vertices(), false),
_cycle{}
{
for (auto v = 0; v < digraph.num_vertices(); ++v) {
if (!_marked[v] && _cycle.empty()) { _dfs(digraph, v); }
}
}
void Directed_cycle::_dfs(const Digraph& digraph, int v)
{
_on_stack[v] = true;
_marked[v] = true;
for (auto w : digraph.adjacent(v)) {
if (!_cycle.empty()) { return; }
else if (!_marked[w]) {
_edge_to[w] = v;
_dfs(digraph, w);
} else if (_on_stack[w]) {
for (auto x = v; x != w; x = _edge_to[x]) { _cycle.push_back(x); }
_cycle.push_back(w);
_cycle.push_back(v);
}
}
_on_stack[v] = false;
}