-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindCycle.java
More file actions
71 lines (61 loc) · 2.02 KB
/
FindCycle.java
File metadata and controls
71 lines (61 loc) · 2.02 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
/**
* Performs depth first search algortihm to detect if there is a cycle.
*/
package graph;
import java.util.ArrayList;
import java.util.HashMap;
// Class to find cycles
public class FindCycle {
/**
* Sets an adjustment list, runs the alorithm to get check for the cycle
* and prints the result.
* @param args Array of arguments for launching the program. Ignored.
* @export
*/
public static void main(String args[]) {
int[][] adjList = {{1, 2}, {1, 3}, {3, 2}, {3, 5}, {5, 1}};
Graph graph = new Graph(adjList);
boolean result = hasCycle(graph, 1);
System.out.println(Boolean.toString(result));
}
/**
* Sets initial varialbes and makes the call for recursive function
* to detect if there is a cycle.
* @param graph The graph to search in.
* @param from The pint where to detect a cycle in.
* @export
*/
static boolean hasCycle(Graph graph, int from) {
ArrayList<Integer> queue = new ArrayList<Integer>();
ArrayList<Integer> explored = new ArrayList<Integer>();
queue.add(from);
return dfSearch(graph, from, queue, explored);
}
/**
* Recursive function: gets element from the queue and checks adjusted
* nodes in search of from point. Otherwise adds the nodes to the the queue.
* @param Graph The graph to search in.
* @param from The point to search cycles for.
* @param queue The queue of elements to research.
* @param explored Already explored nodes.
*/
static boolean dfSearch(Graph graph, int from, ArrayList<Integer> queue, ArrayList<Integer> explored) {
if (queue.size() == 0) {
return false;
}
int curNode = queue.remove(queue.size() - 1);
explored.add(curNode);
ArrayList<Integer> nodes = graph.getNeighborIndexes(curNode);
if (nodes != null) {
for (int node : nodes) {
if (node == from) {
return true;
}
if (explored.indexOf(node) < 0 && queue.indexOf(node) < 0) {
queue.add(node);
}
}
}
return dfSearch(graph, from, queue, explored);
}
}