-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-18 Course Schedule II
67 lines (53 loc) · 1.86 KB
/
Day-18 Course Schedule II
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
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map<Integer,List<Integer>> pre=new LinkedHashMap<>();
for(int[] i: prerequisites){
List<Integer> l=pre.getOrDefault(i[1],new ArrayList<>());
l.add(i[0]);
pre.put(i[1],l);
}
boolean visited[]=new boolean[numCourses];
boolean rec[] =new boolean[numCourses];
for(int i=0;i<numCourses;i++){
if(isCyclic(i,visited,rec,pre)){
return new int[0];
}
}
Stack<Integer> s=new Stack<>();
visited=new boolean[numCourses];
for(int i=0;i<numCourses;i++){
if(!visited[i])
topologicalSort(i,pre,visited,s);
}
int i=0;
int[] result=new int[numCourses];
while(!s.isEmpty()){
result[i++]=s.pop();
}
return result;
}
public void topologicalSort(int node,Map<Integer,List<Integer>> pre,boolean[] visited, Stack<Integer> s){
visited[node]=true;
for(int i:pre.getOrDefault(node,new ArrayList<>())){
if(!visited[i])
topologicalSort(i,pre,visited,s);
}
s.push(node);
}
public boolean isCyclic(int node,boolean[] visited,boolean[] rec,Map<Integer,List<Integer>> pre){
if(!visited[node]){
visited[node]=true;
rec[node]=true;
for(int i:pre.getOrDefault(node,new ArrayList<>())){
if(!visited[i] && isCyclic(i,visited,rec,pre)){
return true;
}
else if(rec[i]){
return true;
}
}
}
rec[node]=false;
return false;
}
}