← Back to DSA Animator
Course Schedule LC #207 Medium Graph · DFS · Cycle Detection
Problem

There are numCourses courses. prerequisites[i]=[a,b] means you must take b before a. Return true if you can finish all courses (no cycle), else false.

Example
Input: n=2, prereqs=[[1,0]]
Output: true
Try Examples
Custom: n / prereqs (a-b)
Approach
DFS Cycle Detection (3-Color)
State: 0=unvisited, 1=visiting (in path), 2=done. If we reach a node with state=1 → back edge → CYCLE.
Graph & State (0=unvis 1=visit 2=done)
Load an example.
Variables
Node u
State[u]
Neighbors
Cycle?
Step Logic
Press ▶ Play or Next Step.
Ready
0/0
Select example and Play.
Algorithm
1
State 1 → back edge → cycle!
2
Mark u visiting, DFS neighbors
3
Mark u done, return false
Time
O(V+E)
Space
O(V)
Why 3-Color

State 1 = "in current DFS path". If we recurse to a node with state 1, we've found a back edge (cycle). State 2 = fully processed, safe to skip.