Depth-First Search (DFS)
A graph traversal that uses a LIFO stack to dive as deep as possible along one path, backtracking when it hits a dead end. It uses little memory (O(h)) and is central to cycle detection, topological sorting, and backtracking-based problem solving.
01Depth-First Search (DFS)
Explore How It WorksStarting DFS. Using a LIFO stack, dive as deep as possible along one path, then backtrack when stuck to try the next. The target is H.
Pop A and expand it. Push neighbors B, C onto the stack — C, pushed last, comes out next.
Pop C. Since C ≠ H, push neighbors F, G onto the stack. Descend deep into the right subtree.
Pop G. It's a leaf node with no neighbors to add, so we must backtrack. Pop the next node off the stack.
Pop F. Since F ≠ H, push neighbor H (C is already visited, so skip it).
Pop H. It matches the target — DFS reached it via A → C → F → H (depth 3).
Search complete · path A → C → F → H (cost 3). Light on memory at O(h), and the basis for cycle detection and backtracking.
02 Understand It Simply
For EveryoneFollows one branch as far as it goes and returns to the last junction when it cannot continue.
Explores one path as deep as possible with a stack, backtracking when stuck.
Uses little memory.
- –Cycle detection
- –topological sorting
- –backtracking problems
03 Python Implementation
A clean, readable reference implementation of the core logic of Depth-First Search (DFS).
04 Frequently Asked Questions
FAQWhat is Depth-First Search (DFS)?+
A graph traversal that uses a LIFO stack to dive as deep as possible along one path, backtracking when it hits a dead end. It uses little memory (O(h)) and is central to cycle detection, topological sorting, and backtracking-based problem solving.
What is the time complexity of Depth-First Search (DFS)?+
The time complexity of Depth-First Search (DFS) is O(V+E). Follow the step-by-step visualization to see exactly why.
Where is Depth-First Search (DFS) used?+
Cycle detection, topological sorting, backtracking problems.
What's a simple analogy for Depth-First Search (DFS)?+
Follows one branch as far as it goes and returns to the last junction when it cannot continue.
