Stage 1 · Code
Graph Algorithms
DFS
Depth-first search for cycle detection, topological ordering, and connectivity.
DFS Basics
DFS explores as deep as possible before backtracking. Uses stack (recursion or explicit). Three states: unvisited (0), visiting (1), visited (2).
Cycle Detection
In directed graph: cycle if we encounter a node in 'visiting' state (gray). In undirected: cycle if neighbor is visited and not parent.
Topological Sort
Linear ordering of DAG vertices where all edges go forward. DFS post-order reversed. Or Kahn's algorithm (BFS with indegree).
Connected Components
Run DFS/BFS from each unvisited node. Each traversal marks one component. Component ID array tracks which component each node belongs to.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.