-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourseSchedule.java
62 lines (53 loc) · 1.54 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
class CourseSchedule {
/*
Runtime: 2 ms, faster than 99.45% of Java online submissions for Course Schedule.
Memory Usage: 39.4 MB, less than 79.99% of Java online submissions for Course Schedule.
*/
List<Integer>[]adjacencylist;
boolean [] visited;
boolean [] explored;
public boolean canFinish(int numCourses, int[][] prerequisites) {
if(prerequisites==null||prerequisites.length==0) return true;
adjacencylist=new ArrayList[numCourses];
for(int i=0;i<numCourses;i++)
{
adjacencylist[i]=new ArrayList<>();
}
visited=new boolean[numCourses];
explored=new boolean[numCourses];
for(int i=0;i<prerequisites.length;i++)
{
adjacencylist[prerequisites[i][0]].add(prerequisites[i][1]);
}
for(int i=0;i<numCourses;i++)
{
if(!visited[i])
{
if(isCycle(i)){
return false;
}
}
}
return true;
}
public boolean isCycle(int n)
{
visited[n]=true;
for(Integer j: adjacencylist[n])
{
if(!visited[j])
{
if(isCycle(j))
{
return true;
}
}
else if(!explored[j])
{
return true;
}
}
explored[n]=true;
return false;
}
}