-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGraph2.java
76 lines (44 loc) · 1.78 KB
/
Graph2.java
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
// This is the auxiliary class for the alternative graph structure,
// based on adjacency lists and used for validating I/I candidates.
package od;
import java.util.*;
public class Graph2 {
private Map<Long, Set<Long>> adj;
public Graph2(Map<Long, Set<Long>> adj) {
this.adj = adj;
}
public boolean isCyclic(){
Map<Long, Integer> visited = new HashMap<>();
for(Long key: adj.keySet()){
visited.put(key, 0);
}
Iterator it = visited.entrySet().iterator();
while(it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if(visited.get(pair.getKey()) == 2){
continue;
}
Long startNode = (Long)pair.getKey();
Stack<AbstractMap.SimpleEntry<Long, Integer>> stack = new Stack<>();
stack.push(new AbstractMap.SimpleEntry<>(startNode, 0));
while (!stack.isEmpty()) {
AbstractMap.SimpleEntry<Long, Integer> currNode = stack.pop();
if(currNode.getValue() == 1){
visited.put(currNode.getKey(), 2);
continue;
}
visited.put(currNode.getKey(), 1);
stack.push(new AbstractMap.SimpleEntry<>(currNode.getKey(), 1));
Set<Long> children = adj.get(currNode.getKey());
for (Long child : children) {
if (visited.get(child) == 0) {
stack.add(new AbstractMap.SimpleEntry<>(child, 0));
} else if(visited.get(child) == 1){
return true;
}
}
}
}
return false;
}
}