Depth-First Search (DFS)
DFS is one of the most important graph algorithms because it is the foundation for many higher-level ideas: detecting cycles, building topological order, identifying strongly connected components, and classifying edges.
This page includes two demos: first, a guided DFS traversal; second, a “Non-tree Edge Analysis” demo showing how DFS produces edge types that explain graph relationships.
Quick Facts
What the Demos Emphasize
- Traversal state: which node is active, which nodes are discovered, and when backtracking happens.
- Tree vs non-tree edges: edges chosen by DFS become the DFS tree; other edges reveal structure.
- Readable reasoning: each step is paired with a short explanation (“why this edge next?”).
Demo 1 — DFS Traversal
What to watch for
Notice how DFS commits to one path “deep” until no unvisited neighbor remains, then backtracks to the most recent branching point. This behavior is what makes DFS powerful for discovering structure in graphs.
DFS Rules (Beginner-Friendly)
- Start at a node and mark it visited.
- Choose an unvisited neighbor and move to it.
- Repeat until the current node has no unvisited neighbors.
- Backtrack to the previous node (stack/recursion) and continue exploring.
- Stop when all reachable nodes are visited (or restart from another node if needed).
Demo 2 — Non-tree Edge Analysis
What this explains
DFS creates a DFS tree from the edges it uses to discover new nodes. All other edges are non-tree edges. Classifying them helps explain cycles, ancestry, and directionality.
Non-tree Edges: The Rules
Outcome
After these two demos, learners can follow DFS traversal with confidence and explain what non-tree edges mean. This prepares them for advanced topics like cycle detection, topological sorting, and strongly connected components.