我總共有numCourses門課(0到n-1),和一個先修課程列表prerequisites[i]=[ai,bi],a代表的是我想修的課,b表示我必需先修的課。
然後我要做的就是判斷我是否有修完所有課程。
那我這次參考的程式碼是用Kahn演算法
它模擬了我們「修課」的過程:
找出所有可以直接修的課,就是這些是沒有任何先修課程要求的課。
class Solution {
public boolean canFinish(int n, int[][] prerequisites) {
List<Integer>[] adj = new List[n];// adj[i]:以 i 為先修課的課程清單
int[] indegree = new int[n]; // indegree[i]:課程 i 需要的先修課數量
// 建立圖
for (int[] p : prerequisites) {
int course = p[0], pre = p[1];
if (adj[pre] == null) adj[pre] = new ArrayList<>();
adj[pre].add(course);
indegree[course]++;
}
// 將指向a的邊為 0的課放入 queue
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++)
if (indegree[i] == 0) q.offer(i);
// BFS 拓撲排序
int count = 0; // 已修課程數
while (!q.isEmpty()) {
int cur = q.poll();
count++;
if (adj[cur] != null) {
for (int next : adj[cur]) {
if (--indegree[next] == 0) q.offer(next);
}
}
}
// 修完所有課,無環,回傳 true
return count == n;
}
}