-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0210-course-schedule-ii.java
51 lines (42 loc) · 1.39 KB
/
0210-course-schedule-ii.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
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map<Integer, List<Integer>> adjList = new HashMap<Integer, List<Integer>>();
int[] indegree = new int[numCourses];
int[] topologicalOrder = new int[numCourses];
//creating the adjlist
for (int i = 0; i < prerequisites.length; i++) {
int post = prerequisites[i][0];
int pre = prerequisites[i][1];
List<Integer> lst = adjList.getOrDefault(
pre,
new ArrayList<Integer>()
);
lst.add(post);
adjList.put(pre, lst);
indegree[post] += 1;
}
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
q.add(i);
}
}
int i = 0;
while (!q.isEmpty()) {
int node = q.remove();
topologicalOrder[i++] = node;
if (adjList.containsKey(node)) {
for (Integer neighbor : adjList.get(node)) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
q.add(neighbor);
}
}
}
}
if (i == numCourses) {
return topologicalOrder;
}
return new int[0];
}
}