A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Depth-First Search (DFS)

College Depth 85 in the knowledge graph ☐ I know this ☆ Set as goal
159topics build on this
439prerequisites beneath it
See this on the map →
Graph Representations: Adjacency List vs. Adjacency MatrixRecursion Basics+2 more→→Articulation Points and Bridges in GraphsBacktracking Search for CSPs+4 more
DFS graph-traversal recursion cycle-detection connected-components

Core Idea

Depth-first search (DFS) explores a graph by going as deep as possible along each branch before backtracking. It can be implemented recursively or iteratively with an explicit stack, and runs in O(V + E) time. DFS is the foundation for cycle detection, topological sorting, strongly connected components (Tarjan's and Kosaraju's algorithms), and solving maze-like problems. Tracking discovery and finish times during DFS produces edge classifications: tree edges, back edges (cycles), forward edges, and cross edges.

How It's Best Learned

Implement recursive DFS tracking discovery and finish timestamps. Then implement the iterative stack version and verify equivalent results. Use DFS to detect cycles in both directed and undirected graphs as a practical exercise.

Common Misconceptions

Explainer

If you have written recursive tree traversals (like inorder or postorder), you have already implemented a special case of depth-first search — trees are acyclic graphs, and DFS on a tree is exactly what those traversals do. Generalizing to arbitrary graphs requires only one addition: a visited set to avoid processing the same node twice (and to prevent infinite loops in cyclic graphs).

The DFS algorithm works like this: start at a source node, mark it visited, then recursively visit each unvisited neighbor before returning. The "depth-first" name captures the behavior — you commit fully to one branch, following it to its dead end, before backtracking and trying another. The call stack (or an explicit stack data structure if implemented iteratively) holds the current path from the source to wherever you are. This is fundamentally different from BFS, which explores level by level. Neither is universally better — they answer different questions.

DFS has a remarkable side effect: the order in which nodes are *entered* (discovery time) and *exited* (finish time) produces a classification of every edge in the graph. A tree edge is one you traverse to an unvisited node. A back edge points from a node to an ancestor currently on the stack — finding one proves a cycle exists in the directed graph. Forward and cross edges cover other cases. This edge classification is the foundation for algorithms like topological sort (process nodes in reverse finish-time order) and strongly connected components (Tarjan's algorithm uses discovery and finish times directly).

Cycle detection deserves special care. In an undirected graph, any edge to an already-visited node that isn't your direct parent means a cycle exists (you reached the same node via two different paths). In a directed graph, the rule is stricter: only a back edge — one that points to a node still on the active recursion stack — proves a cycle. A directed edge to a node that was visited in a previous DFS branch (a cross edge) doesn't create a cycle, because that edge goes from one branch to another, not backward along the current path.

The O(V + E) time complexity follows naturally from the algorithm's structure: each vertex is visited exactly once, and each edge is examined exactly once when its source vertex is being processed. This makes DFS efficient even on large sparse graphs, and it's why DFS is the go-to building block for so many graph algorithms.

Practice Questions 3 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Tree Structure and Node Properties → Binary Trees → Tree Traversals → Depth-First Search (DFS)

Longest path: 86 steps · 439 total prerequisite topics

Prerequisites (4)

Leads To (6)