Course Schedule (Cycle Detection)
mediumGraphs+20 XPTime limit 2s
There are n courses numbered 0 … n−1. A prerequisite pair a b means you must finish course b before course a. Can you finish all the courses?
Input:
- line 1:
n m - next
mlines: a prerequisite paira b
Output: true if all courses can be finished, false otherwise.
Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ m ≤ 10⁵, a ≠ b; a pair may appear more than once.
Think about it: you can finish everything exactly when the prerequisite graph has no cycle. Detect it with Kahn's algorithm (repeatedly take courses with no remaining prerequisites) or with a DFS that colours nodes white/grey/black.
Sample input 1
2 1 1 0
Sample output 1
true
Sample input 2
2 2 1 0 0 1
Sample output 2
false
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).