-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedCycle.h
More file actions
50 lines (45 loc) · 1.11 KB
/
DirectedCycle.h
File metadata and controls
50 lines (45 loc) · 1.11 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
#pragma once
#include <vector>
#include "Digraph.h"
/*
* Find a cycle in a directed graph
*/
class DirectedCycle
{
using Bag = std::vector<int>;
std::vector<bool> marked;
std::vector<int> edgeTo;
std::vector<int> onStack;
Bag m_cycle;
public:
DirectedCycle(Digraph& G)
: marked(G.V(), false), edgeTo(G.V()), onStack(G.V())
{
for (int v = 0; v < G.V(); ++v)
if (!marked[v] && !hasDirectedCycle())
dfs(G, v);
}
bool hasDirectedCycle() {
return !m_cycle.empty();
}
Bag cycle() {
return m_cycle;
}
void dfs(Digraph& G, int v) {
onStack[v] = true;
marked[v] = true;
for (int w : G.adj(v)) {
if (!m_cycle.empty()) return;
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
} else if (onStack[w]) {
for (int x = v; x != w; x = edgeTo[x])
m_cycle.push_back(x);
m_cycle.push_back(w);
m_cycle.push_back(v);
}
}
onStack[v] = false;
}
};