-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourseSchedule.java
75 lines (62 loc) · 1.63 KB
/
CourseSchedule.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
package graph;
import java.util.*;
/**
* @author Shogo Akiyama
* Solved on 08/15/2019
*
* 207. Course Schedule
* https://leetcode.com/problems/course-schedule/
* difficulty: Medium
*
* Approach: DFS & Recursion
* Runtime: 17 ms, faster than 40.17% of Java online submissions for Course Schedule.
* Memory Usage: 46.1 MB, less than 62.31% of Java online submissions for Course Schedule.
*
* Time Complexity: O(n^2)
* Space Complexity: O(n^2) for the recursive stack
* Where n is the number of nodes in a graph
*
* @see GraphTest#testCourseSchedule()
*/
public class CourseSchedule {
private Map<Integer, HashSet<Integer>> graph = new HashMap<Integer, HashSet<Integer>>();
private Set<Integer> seen = new TreeSet<Integer>();
private int count;
public boolean canFinish(int numCourses, int[][] prerequisites) {
for (int i = 0; i < prerequisites.length; i++) {
int[] pair = prerequisites[i];
if (!graph.containsKey(pair[0])) {
graph.put(pair[0], new HashSet<Integer>());
}
if (!graph.containsKey(pair[1])) {
graph.put(pair[1], new HashSet<Integer>());
}
graph.get(pair[0]).add(pair[1]);
}
Set<Integer> passed = new TreeSet<Integer>();
count = numCourses;
for (Integer node : graph.keySet()) {
if (!seen.contains(node)) {
dfs(node, passed);
if (count < 0) {
return false;
}
}
}
return true;
}
void dfs(Integer node, Set<Integer> path) {
seen.add(node);
path.add(node);
for (Integer i : graph.get(node)) {
if (seen.contains(i) && path.contains(i)) {
count = -1;
return;
}
if (!seen.contains(i)) {
dfs(i, path);
}
}
path.remove(node);
}
}