A project has n tasks, numbered 1 to n, and m dependency rules. Each rule u v means task u must be completed before task v can start. A dependency edge is one-way (directed): u v does NOT imply v must precede u.
The rules are a deadlock if there is no way to complete all tasks one at a time while respecting every rule — equivalently, the directed dependency graph contains a cycle. Rules may repeat, and a rule may even point a task at itself (u v with u = v), which is always a deadlock on its own.
Determine whether the dependencies are deadlocked.
Line 1: two integers n and m — number of tasks (1-indexed) and number of rules.
Next m lines: two integers u v — a directed rule meaning task u precedes task v.
A single integer: 1 if the dependencies contain a cycle (deadlock), 0 otherwise.
Example 1
Input
3 3 1 2 2 3 3 1
Expected
1
Explanation
Task 1 depends on 3, which depends on 2, which depends on 1: a deadlock. Output 1.
Example 2
Input
3 2 1 2 2 3
Expected
0
Explanation
A simple chain 1 -> 2 -> 3 with no cycle. Output 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →