-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathSolution.java
More file actions
87 lines (82 loc) · 2.89 KB
/
Copy pathSolution.java
File metadata and controls
87 lines (82 loc) · 2.89 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
87
/**
* Time : O(); Space : O()
* @tag : Depth-first Search; Breadth-first Search; Graph; Topological Sort
* @by : Steven Cooks
* @date: Jun 26, 2015
*************************************************************************
* Description:
*
* There are a total of n courses you have to take, labeled from 0 to n - 1.
* Some courses may have prerequisites, for example to take course 0 you have to
* first take course 1, which is expressed as a pair: [0,1]
*
* Given the total number of courses and a list of prerequisite pairs,
* is it possible for you to finish all courses?
*
* For example:
*
* 2, [[1,0]]
* There are a total of 2 courses to take. To take course 1 you should have
* finished course 0. So it is possible.
*
* 2, [[1,0],[0,1]]
* There are a total of 2 courses to take. To take course 1 you should have
* finished course 0, and to take course 0 you should also have finished
* course 1. So it is impossible.
*
*************************************************************************
* {@link https://leetcode.com/problems/course-schedule/ }
*/
package _207_CourseSchedule;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
/** see also {@link _207_CourseSchedule.SolutionDFS DFS version solution } */
public class Solution {
/*
* 1. construct topological graph 2. count in-degrees for each node 3. for
* zero in-degree nodes, put them to queue 4. BFS search if all nodes become
* zero in-degree
*/
public boolean canFinish(int numCourses, int[][] prerequisites) {
// initialize graph
List<Set<Integer>> graph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
graph.add(new HashSet<>());
}
// construct graph and count in-degrees for each node
int[] indegrees = new int[numCourses];
for (int[] is : prerequisites) {
if (graph.get(is[0]).add(is[1])) {
// !avoid duplicates. Alternatively, make graph
// List<List<Integer>>
indegrees[is[1]]++;
}
}
// push all 0 in-degree nodes into queue
Queue<Integer> zeros = new LinkedList<>();
for (int i = 0; i < indegrees.length; i++) {
if (indegrees[i] == 0) {
zeros.add(i);
}
}
// BFS
int count = 0;
while (!zeros.isEmpty()) {
int course = zeros.poll();
count++;
for (int request : graph.get(course)) {
// count down in-degree for this prerequisite by one
// and then if it is zero
indegrees[request]--;
if (indegrees[request] == 0) {
zeros.add(request);
}
}
}
return count == numCourses;
}
}