-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleInGraph.java
More file actions
42 lines (39 loc) · 1003 Bytes
/
CycleInGraph.java
File metadata and controls
42 lines (39 loc) · 1003 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
42
import java.util.*;
class Program {
// O(v + e) time | O(v) space - where v is the number of vertices
// and e is the number of edges in the graph
public boolean cycleInGraph(int[][] edges) {
// Write your code here.
State[] states = new State[edges.length];
for (int v = 0; v < edges.length; v++) {
states[v] = State.TO_VISIT;
}
for (int v = 0; v < edges.length; v++) {
boolean containsCycle = dfs(v, edges, states);
if (containsCycle) {
return true;
}
}
return false;
}
private static boolean dfs(int node, int[][] edges, State[] states) {
if (states[node].equals(State.VISITED)) {
return false;
}
if (states[node].equals(State.VISITING)) {
return true;
}
states[node] = State.VISITING;
for (int neighbor : edges[node]) {
boolean containsCycle = dfs(neighbor, edges, states);
if (containsCycle) {
return true;
}
}
states[node] = State.VISITED;
return false;
}
private static enum State {
TO_VISIT, VISITING, VISITED;
}
}