aboutsummaryrefslogtreecommitdiff
path: root/CourseSchedule.java
diff options
context:
space:
mode:
Diffstat (limited to 'CourseSchedule.java')
-rw-r--r--CourseSchedule.java46
1 files changed, 23 insertions, 23 deletions
diff --git a/CourseSchedule.java b/CourseSchedule.java
index 5b5ed02..6f85f44 100644
--- a/CourseSchedule.java
+++ b/CourseSchedule.java
@@ -3,9 +3,26 @@ import java.util.*;
import node.*;
class CourseSchedule {
- public static boolean canFinish(int[][] prerequisites) {
- GraphNode node = createGraph(prerequisites);
- return !detectCycle(node);
+ public static boolean detectCycle(GraphNode node) {
+ Stack<GraphNode> stack = new Stack<GraphNode>();
+ ArrayList<GraphNode> visited = new ArrayList<GraphNode>();
+ stack.push(node);
+ while (!stack.empty()) {
+ node = stack.pop();
+ if (visited.contains(node)) {
+ System.out.println("Cycle " + node.val);
+ return true;
+ }
+ visited.add(node);
+ System.out.println("Node: " + node.val);
+ System.out.print("Neighbors: ");
+ for (GraphNode neighbor : node.neighbors) {
+ stack.push(neighbor);
+ System.out.print(neighbor.val + " ");
+ }
+ System.out.println();
+ }
+ return false;
}
public static GraphNode createGraph(int[][] prerequisites) {
@@ -31,26 +48,9 @@ class CourseSchedule {
return map.get(1);
}
- public static boolean detectCycle(GraphNode node) {
- Stack<GraphNode> stack = new Stack<GraphNode>();
- ArrayList<GraphNode> visited = new ArrayList<GraphNode>();
- stack.push(node);
- while (!stack.empty()) {
- node = stack.pop();
- if (visited.contains(node)) {
- System.out.println("Cycle " + node.val);
- return true;
- }
- visited.add(node);
- System.out.println("Node: " + node.val);
- System.out.print("Neighbors: ");
- for (GraphNode neighbor : node.neighbors) {
- stack.push(neighbor);
- System.out.print(neighbor.val + " ");
- }
- System.out.println();
- }
- return false;
+ public static boolean canFinish(int[][] prerequisites) {
+ GraphNode node = createGraph(prerequisites);
+ return !detectCycle(node);
}
public static void main(String[] args) {