-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse Schedule.java
More file actions
50 lines (47 loc) · 1.31 KB
/
Copy pathCourse Schedule.java
File metadata and controls
50 lines (47 loc) · 1.31 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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
HashMap<Integer, ArrayList<Integer>> map =new HashMap<Integer, ArrayList<Integer>>();
int[] visited = new int[numCourses];
if(prerequisites == null || numCourses == 0)
return true;
for(int a[] : prerequisites)
{
if(map.containsKey(a[1]))
{
map.get(a[1]).add(a[0]);
}
else {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a[0]);
map.put(a[1], list);
}
}
for(int i = 0; i<numCourses; i++)
{
if(!helperFunc(i, map, visited))
{
return false;
}
}
return true;
}
static boolean helperFunc(int i, HashMap<Integer, ArrayList<Integer>> map, int[] visited)
{
if(visited[i] == -1)
return false;
if(visited[i] == 1)
return true;
visited[i] = -1;
if(map.containsKey(i)) {
for(int j : map.get(i))
{
if(!helperFunc(j, map, visited))
{
return false;
}
}
}
visited[i] = 1;
return true;
}
}