24. Detect Cycle in Module Dependency Graph
Origin: Detect Cycle in Module Dependency Graph
Given n modules labeled 0 to n-1 and a list of directed edges dependencies where [u, v] means module u depends on module v, return 1 if there is a cycle in the dependency graph, otherwise return 0.
Example 1
Input: n = 4, dependencies = [[1, 0], [2, 1], [3, 2]]
Output: 0
Explanation: 边为 1→0, 2→1, 3→2。形成一条简单链,没有模块间接或直接依赖自己,无环,返回 0。
Example 2
Input: n = 4, dependencies = [[1, 0], [2, 1], [0, 2]]
Output: 1
Explanation: 边为 1→0, 2→1, 0→2。0 依赖 2,2 依赖 1,1 依赖 0。形成环 0→2→1→0,返回 1。
Input Format
- 第一行:n(模块数量)
- 第二行:dependencies_rows(依赖数组行数)
- 第三行:dependencies_columns(依赖数组列数)
- 接下来 dependencies_rows 行:每行两个整数 u v,表示 u 依赖 v
Constraints
- 1 <= n <= 1000
- 0 <= dependencies.length <= n * (n - 1)
- dependencies[i].length == 2
- 0 <= dependencies[i][0] < n
- 0 <= dependencies[i][1] < n
- dependencies 可能包含重复对
- 自依赖(u == v)是允许的,且算作环
Output Format
返回 1(有环)或 0(无环)。
Sample Input 0
1
0
0
Sample Output 0
0
Sample Input 1
1
1
2
0
0
Sample Output 1
1
函数契约
// 输入:n(节点数),dependencies(有向边列表,[u, v] 表示 u → v)
// 输出:1(有环)或 0(无环)
// 边界:无依赖 → 0;自依赖 u==v → 1;简单链 → 0;环 → 1
边界表
| 场景 | 返回什么 |
|---|---|
| 无依赖 | 0 |
| 自依赖(u == v) | 1 |
| 简单链 | 0 |
| 有环 | 1 |
| 无环 | 0 |
Resolution
我的解法
// TODO: 在这里填写你的解法解题思路
待填写。
复杂度
待填写。
参考来源
- 相关题型:图论
- 相关文章:算法解题流程:从读题到提交的七步
- 相关题目:21. Count Connected Components in Network — 同样是图论 DFS