You are given n tasks labeled from 0 to n - 1 and a list of dependencies prerequisites, where prerequisites[i] = [a, b] means task a depends on task b (task b must be completed before task a).
Return True if there is a circular dependency among the tasks, and False otherwise.
A circular dependency exists when, following the dependency edges, you can start from some task and return to it.
Function Signature
def has_circular_dependency(n: int, prerequisites: list[list[int]]) -> bool:
Rules
-
A pair
[a, a]
(a task that depends on itself) counts as a circular dependency.
-
A cycle anywhere among the
n
tasks counts, including one in a group of tasks that has no dependency link to the others.
Constraints
-
1 <= n <= 10^4
-
0 <= len(prerequisites) <= 10^5
-
Each pair has exactly two entries, and
0 <= a, b < n
.
-
All pairs
[a, b]
are distinct.
Examples
Input: n = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]
Output: True
Task 0 depends on 1, task 1 depends on 2, and task 2 depends on 0. Following the dependencies from task 0 leads back to task 0.
Input: n = 4, prerequisites = [[1, 0], [2, 1], [3, 2]]
Output: False
The dependencies form a chain, so the tasks can be completed in the order 0, 1, 2, 3 and no task leads back to itself.
Input: n = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: False
Task 3 depends on tasks 1 and 2, and both of them depend on task 0. Reaching task 0 along two different paths is not a cycle, and the tasks can run in the order 0, 1, 2, 3.