Repository navigation
Expand file tree
/
Copy pathDirectedGraph.java
More file actions
86 lines (73 loc) · 2.15 KB
/
Copy pathDirectedGraph.java
File metadata and controls
86 lines (73 loc) · 2.15 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
83
84
85
86
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;
public class DirectedGraph implements Graph{
private HashSet<GraphNode> allNodes;
public DirectedGraph() {
allNodes = new HashSet<>();
}
public void addNode(final int nodeVal)
{
GraphNode node = new GraphNode(nodeVal);
allNodes.add(node);
}
public void addDirectedEdge(final GraphNode first, final GraphNode second)
{
Edge edge = new Edge(second, 1);
first.neighbors.add(edge);
}
public void removeDirectedEdge(final GraphNode first, final GraphNode second)
{
for (Edge edge : first.neighbors) {
if (edge.destination == second) {
first.neighbors.remove(edge);
break;
}
}
}
public HashSet<GraphNode> getAllNodes()
{
return allNodes;
}
public GraphNode get(int element)
{
for (GraphNode node : allNodes) {
if (node.value == element)
return node;
}
return null;
}
static boolean checkCycles(Graph graph, GraphNode node) {
Stack<GraphNode> stack = new Stack<>();
GraphNode curr = node;
boolean cycle = true; // true is no cycle, false is yes cycle
// Modified DFS that checks for cycles
do
{
// If already visited, continue
if (curr.visited)
{
continue;
}
curr.visited = true;
int count=0;
// Add each edge to the stack
for (Edge edge : curr.neighbors)
{
if (!edge.destination.visited) {
stack.push(edge.destination);
count++;
}
}
node.visited = false;
if (stack.isEmpty())
break;
if (stack.contains(node)) {
cycle = false;
break;
}
curr = stack.pop();
} while (curr != node);
return cycle;
}
}