-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycle.h
More file actions
82 lines (73 loc) · 1.96 KB
/
Cycle.h
File metadata and controls
82 lines (73 loc) · 1.96 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#pragma once
#include <vector>
#include "Graph.h"
/*
* Find a cycle in an undirected graph
*/
class Cycle
{
using Bag = std::vector<int>;
std::vector<bool> marked;
std::vector<int> edgeTo;
Bag m_cycle;
public:
Cycle(Graph& G) {
if (hasSelfLoop(G)) return;
marked.reserve(G.V());
for (int v = 0; v < G.V(); ++v) marked[v] = false;
if (hasParallelEdges(G)) return;
edgeTo.reserve(G.V());
for (int v = 0; v < G.V(); ++v)
if (!marked[v] && !hasCycle())
dfs(G, -1, v);
else
return;
}
bool hasSelfLoop(Graph& G) {
for (int v = 0; v < G.V(); ++v)
for (int w : G.adj(v))
if (v == w) {
m_cycle.push_back(v);
m_cycle.push_back(v);
return true;
}
return false;
}
bool hasParallelEdges(Graph& G) {
for (int v = 0; v < G.V(); ++v) {
for (int w : G.adj(v)) {
if (marked[w]) {
m_cycle.push_back(v);
m_cycle.push_back(w);
m_cycle.push_back(v);
return true;
}
marked[w] = true;
}
for (int w : G.adj(v))
marked[w] = false;
}
return false;
}
bool hasCycle() {
return !m_cycle.empty();
}
Bag cycle() {
return m_cycle;
}
void dfs(Graph& G, int u, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!m_cycle.empty()) return;
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, v, w);
} else if (u != 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);
}
}
}
};