Intermediate Topic 32 of 51 Algorithms
Depth-First Search
Exploring a graph as deep as possible before backtracking.
How it works
Depth-first search explores as far as possible along each branch before backtracking, using recursion or an explicit stack. It records discovery and finishing times, runs in O(V + E) and classifies edges as tree, back, forward or cross edges, which reveals cycles and structure. Memory is proportional to the path depth.
Where it is used
Detecting cycles, topological sorting, finding connected and strongly connected components, solving mazes, backtracking search, finding articulation points and bridges and traversing file systems use DFS.
Common pitfall
Recursive DFS can overflow the stack on deep graphs, so use an explicit stack. Forgetting a visited set causes infinite loops on cyclic graphs. DFS does not find shortest paths. Handle disconnected graphs by starting a search from every unvisited vertex.
Where it fits in the course
Depth-First Search is topic 32 of 51 in Algorithms, rated Intermediate. It follows Breadth-First Search. The next topic is Topological Sort.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
- Explore the Graph Traversal visualizer: BFS, DFS and Dijkstra on a weighted graph.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Depth-First Search?
Where do people use Depth-First Search?
What is the most common mistake with Depth-First Search?
What should I learn before this topic?
How can I practice it?
Is Depth-First Search hard to learn?
How long does it take to learn Depth-First Search?
Which topics are related to Depth-First Search?
What should I study after Depth-First Search?
Related topics
- Breadth-First Search (Algorithms)
- Topological Sort (Algorithms)
- N-Queens Problem (Algorithms)
- Dijkstra's Algorithm (Algorithms)
- Search Engines (Emerging & Frontier Topics)
- Shortest Job First (Operating Systems)
- Binary Search Trees (Data Structures)