Skip to content

Commit a5a837c

Browse files
authored
Merge pull request neetcode-gh#165 from r1cky0/patch-11
Create 207-Course-Schedule.java
2 parents 8eebdab + e8c513d commit a5a837c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

java/207-Course-Schedule.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public boolean canFinish(int numCourses, int[][] prerequisites) {
3+
List<List<Integer>> adj = new ArrayList<>();
4+
for (int i = 0; i < numCourses; i++) {
5+
adj.add(new ArrayList<>());
6+
}
7+
8+
for (int i = 0; i < prerequisites.length; i++) {
9+
adj.get(prerequisites[i][0]).add(prerequisites[i][1]);
10+
}
11+
12+
int[] visited = new int[numCourses];
13+
for (int i = 0; i < numCourses; i++) {
14+
if (visited[i] == 0) {
15+
if (isCyclic(adj, visited, i)) {
16+
return false;
17+
}
18+
}
19+
}
20+
return true;
21+
}
22+
23+
private boolean isCyclic(List<List<Integer>> adj, int[] visited, int curr) {
24+
if (visited[curr] == 2) {
25+
return true;
26+
}
27+
28+
visited[curr] = 2;
29+
for (int i = 0; i < adj.get(curr).size(); i++) {
30+
if (visited[adj.get(curr).get(i)] != 1) {
31+
if (isCyclic(adj, visited, adj.get(curr).get(i))) {
32+
return true;
33+
}
34+
}
35+
}
36+
visited[curr] = 1;
37+
return false;
38+
}
39+
}

0 commit comments

Comments
 (0)