|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
3 | 5 | import java.util.HashSet;
|
4 | 6 | import java.util.Iterator;
|
5 | 7 | import java.util.LinkedList;
|
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
6 | 10 | import java.util.Queue;
|
7 | 11 | import java.util.Set;
|
8 | 12 |
|
@@ -85,4 +89,46 @@ public boolean canFinish(int numCourses, int[][] prerequisites) {
|
85 | 89 | return true;
|
86 | 90 | }
|
87 | 91 | }
|
| 92 | + |
| 93 | + public static class Solution3 { |
| 94 | + /** |
| 95 | + * DFS, the fastest method in all, with the help of a cache and also converted edges into adjacency list, |
| 96 | + * although theoretically, all these three methods' time complexity is: O(V+E) |
| 97 | + */ |
| 98 | + public boolean canFinish(int numCourses, int[][] prerequisites) { |
| 99 | + List<List<Integer>> courseList = new ArrayList<>(); |
| 100 | + for (int i = 0; i < numCourses; i++) { |
| 101 | + courseList.add(new ArrayList<>()); |
| 102 | + } |
| 103 | + for (int[] pre : prerequisites) { |
| 104 | + courseList.get(pre[1]).add(pre[0]); |
| 105 | + } |
| 106 | + int[] visited = new int[numCourses]; |
| 107 | + //visit each course using DFS |
| 108 | + for (int i = 0; i < numCourses; i++) { |
| 109 | + if (!dfs(i, courseList, visited)) { |
| 110 | + return false; |
| 111 | + } |
| 112 | + } |
| 113 | + return true; |
| 114 | + } |
| 115 | + |
| 116 | + private boolean dfs(int course, List<List<Integer>> courseList, int[] visited) { |
| 117 | + visited[course] = 1;//mark as temporarily visited |
| 118 | + List<Integer> coursesCanBeTaken = courseList.get(course); |
| 119 | + for (int i = 0; i < coursesCanBeTaken.size(); i++) { |
| 120 | + int courseToTake = coursesCanBeTaken.get(i); |
| 121 | + if (visited[courseToTake] == 1) { |
| 122 | + return false; |
| 123 | + } |
| 124 | + if (visited[courseToTake] == 0) { |
| 125 | + if (!dfs(courseToTake, courseList, visited)) { |
| 126 | + return false; |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + visited[course] = 2;//mark it as completely done. |
| 131 | + return true; |
| 132 | + } |
| 133 | + } |
88 | 134 | }
|
0 commit comments