DSA AnimatorDSA animations
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.

How to solve Course Schedule

LeetCode 207 · Medium · Graph · Pattern: Topological Sort

Why the obvious approach is slow

Trying every order of the courses is n factorial, which is hopeless. The real question is whether the prerequisite graph has a cycle.

The key idea

Draw an arrow from each prerequisite to the course that needs it. For every course, count its in degree, which is how many prerequisites it still waits for. Courses with in degree 0 can be taken right now, so put them in a queue. Taking a course removes its outgoing arrows, which lowers the in degree of the courses after it. If every course is eventually taken, there is no cycle.

Remember

A schedule exists exactly when the graph has no cycle. Kahn’s algorithm takes nodes with in degree 0, one by one.

Run the animation above on your own input, or watch the 2:03 video explanation of Course Schedule with a dry run and Java code.

More Graph problems