-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse Schedule
More file actions
101 lines (99 loc) · 3.18 KB
/
Course Schedule
File metadata and controls
101 lines (99 loc) · 3.18 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//DFS way
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
boolean[] isExplored = new boolean[numCourses];
for(int i = 0; i < numCourses; i++){
adj.add(i, new ArrayList<Integer>());
}
for(int i = 0; i < prerequisites.length; i++){
adj.get(prerequisites[i][0]).add(prerequisites[i][1]);
}
for(int i = 0; i < numCourses; i++){
if(!DFS(i, isExplored, adj)){
return false;
}
}
return true;
}
private boolean DFS(int s, boolean[] isExplored, ArrayList<ArrayList<Integer>> adj){
if(isExplored[s]){
return false;
}else{
isExplored[s] = true;
}
for(int v : adj.get(s)){
if(!DFS(v, isExplored, adj)){
return false;
}
}
isExplored[s] = false; /////////////////////// change to false, for next loop
return true;
}
}
//DFS Optimized
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
boolean[] isExplored = new boolean[numCourses];
for(int i = 0; i < numCourses; i++){
adj.add(i, new ArrayList<Integer>());
}
for(int i = 0; i < prerequisites.length; i++){
adj.get(prerequisites[i][0]).add(prerequisites[i][1]);
}
for(int i = 0; i < numCourses; i++){
if(!DFS(i, isExplored, adj)){
return false;
}
}
return true;
}
private boolean DFS(int s, boolean[] isExplored, ArrayList<ArrayList<Integer>> adj){
isExplored[s] = true;
for(int v : adj.get(s)){
if(isExplored[v]){
return false;
}else{
if(!DFS(v, isExplored, adj)){
return false;
}
}
}
isExplored[s] = false;
return true;
}
}
//BFS way
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
int[] incoming = new int[numCourses];
int count = 0;
Queue<Integer> frontier = new LinkedList<Integer>();
for(int i = 0; i < numCourses; i++){
adj.add(i, new ArrayList<Integer>());
}
for(int i = 0; i < prerequisites.length; i++){
adj.get(prerequisites[i][0]).add(prerequisites[i][1]);
incoming[prerequisites[i][1]]++;
}
for(int i = 0; i < incoming.length; i++){
if(incoming[i] == 0){
count++;
frontier.add(i);
}
}
while(!frontier.isEmpty()){
int u = frontier.poll();
for(int v : adj.get(u)){
incoming[v]--;
if(incoming[v] == 0){
frontier.add(v);
count++;
}
}
}
return count == numCourses;
}
}