Skip to content

Commit 6fa701f

Browse files
committed
feat: course-schedule
1 parent 1061026 commit 6fa701f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

course-schedule/minji-go.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/course-schedule/">week10-3. course-schedule </a>
3+
* <li>Description: Return true if you can finish all courses. Otherwise, return false </li>
4+
* <li>Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort </li>
5+
* <li>Time Complexity: O(N+E), Runtime 7ms </li>
6+
* <li>Space Complexity: O(N+E), Memory 45.68MB </li>
7+
* <li>Note : refer to the answer. remember the topic of topological sort </li>
8+
*/
9+
class Solution {
10+
public boolean canFinish(int numCourses, int[][] prerequisites) {
11+
int[] inDegree = new int[numCourses];
12+
List<List<Integer>> graph = new ArrayList<>();
13+
for (int i=0; i<numCourses; i++){
14+
graph.add(new ArrayList<>());
15+
}
16+
17+
for(int[] pre : prerequisites) {
18+
int dest = pre[0], src = pre[1];
19+
graph.get(src).add(dest);
20+
inDegree[dest]++;
21+
}
22+
23+
Queue<Integer> queue = new LinkedList<>();
24+
for (int i=0; i<numCourses; i++) {
25+
if(inDegree[i] == 0) {
26+
queue.offer(i);
27+
}
28+
}
29+
30+
int count = 0;
31+
while(!queue.isEmpty()){
32+
int node = queue.poll();
33+
count++;
34+
35+
for(int neighbor : graph.get(node)) {
36+
inDegree[neighbor]--;
37+
if(inDegree[neighbor] == 0) {
38+
queue.offer(neighbor);
39+
}
40+
}
41+
}
42+
43+
return count == numCourses;
44+
}
45+
}

0 commit comments

Comments
 (0)