Course Schedule Visualizer & Step-by-Step Algorithm Solution

Determine if it is possible to finish all courses given prerequisite dependencies using Kahn's algorithm (Topological Sort BFS with in-degree tracking).

Category: graphs | Difficulty: Medium

Tags: Graph, Topological Sort, BFS, Cycle Detection, Kahn's Algorithm

Course Schedule

Drag nodes to arrange
DEPENDENCY GRAPH (4 COURSES)
0
in: 0
1
in: 1
2
in: 1
3
in: 2
READY QUEUE (IN-DEGREE 0)
(Queue Empty)
100%
state
completed0
numCourses4
prerequisites4
Initialization
1/15
Explanation

Initialize dependency graph with 4 courses and 4 prerequisite constraints.

Source Code
1function canFinish(numCourses, prerequisites) {
2 const inDegree = new Array(numCourses).fill(0);
3 const adj = Array.from({ length: numCourses }, () => []);
4 for (const [course, pre] of prerequisites) {
5 adj[pre].push(course);
6 inDegree[course]++;
7 }
8 const queue = [];
9 for (let i = 0; i < numCourses; i++) {
10 if (inDegree[i] === 0) queue.push(i);
11 }
12 let completed = 0;
13 while (queue.length > 0) {
14 const curr = queue.shift();
15 completed++;
16 for (const next of adj[curr]) {
17 inDegree[next]--;
18 if (inDegree[next] === 0) queue.push(next);
19 }
20 }
21 return completed === numCourses;
22}