Algorithms first

课程表 · 交互式算法学习

判断所有课程是否可以修完。

#207 ·

课程表

Course Schedule

测试用例numCourses = 2, prerequisites = [[1,0]]
树 / 图3 个关键状态
步骤 1课程 0 入度为 0,入队。queue=[0]
01
推荐

Kahn 拓扑排序

时间 O(V+E)空间 O(V+E)

入度为 0 的课程先修;逐步删除边,最终处理数应等于课程数。

1function canFinish(n, pre) {2  const g = Array.from({3      length: n4    }, () => []),5    deg = Array(n).fill(0);6  for (const [a, b] of pre) {7    g[b].push(a);8    deg[a]++9  }10  const q = deg.map((d, i) => d ? null : i).filter(x => x !== null);11  let done = 0;12  while (q.length) {13    const x = q.shift();14    done++;15    for (const y of g[x])16      if (--deg[y] === 0) q.push(y)17  }18  return done === n;19}
多语言参考

Java · C++ · Go

来源 · CC BY-SA 4.0 ↗

这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。

1class Solution {2    public boolean canFinish(int numCourses, int[][] prerequisites) {3        List<Integer>[] g = new List[numCourses];4        Arrays.setAll(g, k -> new ArrayList<>());5        int[] indeg = new int[numCourses];6        for (var p : prerequisites) {7            int a = p[0], b = p[1];8            g[b].add(a);9            ++indeg[a];10        }11        Deque<Integer> q = new ArrayDeque<>();12        for (int i = 0; i < numCourses; ++i) {13            if (indeg[i] == 0) {14                q.offer(i);15            }16        }17        while (!q.isEmpty()) {18            int i = q.poll();19            --numCourses;20            for (int j : g[i]) {21                if (--indeg[j] == 0) {22                    q.offer(j);23                }24            }25        }26        return numCourses == 0;27    }28}
交互式算法学习

从执行步骤真正理解 LeetCode 经典 150

本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。

多形态可视化数组、矩阵、DP 表、递归树、树图、链表、栈队列堆、区间和状态机按解法选择。
动画与代码同步当前状态、步骤说明、变量和代码高亮保持一一对应,可逐步播放和回退。
适合面试复习每种方案都给出思路、时间复杂度、空间复杂度、测试用例和 LeetCode 中文原题入口。
AlgoViz Lab

课程表 · 解法对比

判断所有课程是否可以修完。

测试用例
numCourses = 2, prerequisites = [[1,0]]
题目分类
解法对比
2
方案 1

DFS 三色判环

0 未访问、1 搜索中、2 已完成;遇到搜索中节点说明有环。

时间
O(V+E)
空间
O(V)
方案 2

Kahn 拓扑排序

入度为 0 的课程先修;逐步删除边,最终处理数应等于课程数。

时间
O(V+E)
空间
O(V+E)