-
Notifications
You must be signed in to change notification settings - Fork 153
/
cycle_detection_in_graph.cpp
61 lines (56 loc) · 1.44 KB
/
cycle_detection_in_graph.cpp
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
/**
* Description: Cycle Detection (Detects a cycle in a directed or undirected graph.)
* Usage: O(V)
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
using namespace std;
const int MAX = 100005;
enum Color {
gray, white, black
};
typedef vector< vector<int> > Graph;
bool detectCycle(Graph &G, bool isUndirected)
{
Color isVisited[MAX] = {white};
int parent[MAX];
stack<int> S;
for (int i = 0; i < G.size(); i++) {
if (isVisited[i] == black) continue;
S.push(i);
while (!S.empty()) {
int u = S.top();
S.pop();
if (isVisited[u] == gray) {
isVisited[u] = black;
} else {
S.push(u);
isVisited[u] = gray;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (isVisited[v] == white) {
parent[v] = u;
S.push(v);
} else if (isVisited[v] == gray and (!isUndirected or v != parent[u])) {
return true;
}
}
}
}
}
}
int main() {
int v, e;
cin >> v >> e;
Graph G(v);
for (int i = 0; i < e; i++) {
int a, b;
cin >> a >> b;
a--, b--;
G[a].push_back(b);
}
cout << detectCycle(G, false) << endl;
}