知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 94 - 课程表 ## 题目(LeetCode 207) 判断是否可能完成所有课程(检测有向图是否有环)。 ## 解法:拓扑排序(BFS) ```java class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { int[] indegree = new int[numCourses]; List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>()); for (int[] pre : prerequisites) { graph.get(pre[1]).add(pre[0]); indegree[pre[0]]++; } Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (indegree[i] == 0) queue.offer(i); } int count = 0; while (!queue.isEmpty()) { int cur = queue.poll(); count++; for (int next : graph.get(cur)) { if (--indegree[next] == 0) queue.offer(next); } } return count == numCourses; } } ``` ## 复杂度 - 时间 O(V + E),空间 O(V + E) ## 一句话总结 BFS 拓扑排序,若能遍历所有节点则无环,否则存在循环依赖。
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入