-
Notifications
You must be signed in to change notification settings - Fork 0
/
courseSchedule.java
69 lines (59 loc) · 1.91 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
package week4;
import java.util.LinkedList;
import java.util.List;
/***
* There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1.
* You are given an array prerequisites where prerequisites[i] = [ai, bi]
* indicates that you must take course bi first if you want to take course ai.
*
* For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
* Return true if you can finish all courses. Otherwise, return false.
*
*
*
* Example 1:
*
* Input: numCourses = 2, prerequisites = [[1,0]]
* Output: true
* Explanation: There are a total of 2 courses to take.
* To take course 1 you should have finished course 0. So it is possible.
*/
public class courseSchedule {
LinkedList<Integer> adj[];
public boolean canFinish(int numCourses, int[][] prerequisites) {
adj = new LinkedList[numCourses];
for(int i=0;i<numCourses;i++){
adj[i] = new LinkedList<>();
}
for(int i=0;i<prerequisites.length;i++){
adj[prerequisites[i][1]].add(prerequisites[i][0]);
}
if(isCyclic(numCourses)){
return false;
}
return true;
}
public boolean isCyclic(int numcourses){
boolean[] recStack = new boolean[numcourses];
boolean[] visited = new boolean[numcourses];
for(int i=0;i<numcourses;i++){
if(isCyclicUtil(visited, recStack, i))
return true;
}
return false;
}
public boolean isCyclicUtil(boolean[] visited, boolean[] recStack, int i){
if(recStack[i]) return true;
if(visited[i]) return false;
visited[i] = true;
recStack[i] = true;
List<Integer> l = adj[i];
for(Integer k:l){
if(isCyclicUtil(visited, recStack, k)){
return true;
}
}
recStack[i] = false;
return false;
}
}