Depth-First Search Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Python's readability makes it ideal for learning Depth-First Search.
- ✓The implementation achieves O(V + E) average time complexity.
- ✓Python's built-in data structures complement Depth-First Search implementations.
- ✓Type hints improve code clarity and catch bugs early.
- ✓Memory-efficient for deep graphs: O(V) space vs O(V) for BFS
- ✓Topological sorting of directed acyclic graphs
Depth-First Search in Python: Overview
Python Implementation
from collections import defaultdict
def dfs_recursive(graph: dict[int, list[int]], start: int) -> list[int]:
"""Depth-first search using recursion."""
visited: set[int] = set()
order: list[int] = []
def visit(node: int) -> None:
visited.add(node)
order.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
def dfs_iterative(graph: dict[int, list[int]], start: int) -> list[int]:
"""Depth-first search using explicit stack."""
visited: set[int] = set()
stack = [start]
order: list[int] = []
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
order.append(node)
for neighbor in reversed(graph.get(node, [])):
if neighbor not in visited:
stack.append(neighbor)
return order
g = {0: [1, 2], 1: [2], 2: [0, 3], 3: []}
print(dfs_recursive(g, 2)) # [2, 0, 1, 3]Step-by-Step Explanation
Did You Get the Big O Right? NexusBro Will Tell You in Seconds.
Paste your algorithm. Get complexity analysis, edge cases, and optimizations.
Test My AlgorithmComplexity Analysis
Testing Your Implementation
Python-Specific Optimizations
Is Depth-First Search the Right Choice in Python?
Where Python Developers Actually Use Depth-First Search
Frequently Asked Questions
Is Python good for implementing Depth-First Search?
Yes, Python is excellent for learning and implementing Depth-First Search. Its readable syntax makes the algorithm logic clear, and its standard library provides useful supporting data structures. While Python is slower than compiled languages, the asymptotic complexity is identical, making it perfect for understanding and interviews.
How does Python's built-in sort compare to Depth-First Search?
Python's built-in sort uses TimSort, a hybrid merge-sort and insertion-sort algorithm with O(n log n) worst case. Depending on Depth-First Search's complexity class, it may be faster or slower for specific inputs. Built-in sort is highly optimized in C, so it will outperform pure Python implementations.
Should I use type hints in my Depth-First Search Python code?
Yes, type hints improve code readability, enable better IDE support, and help catch type-related bugs early. They are especially valuable in algorithm implementations where the types of inputs and outputs should be clear to readers.
Can I use Depth-First Search in Python for large datasets?
For large datasets, consider the algorithm's complexity. If Depth-First Search has O(V + E) worst case, it may be slow for very large inputs. Python's NumPy and Pandas libraries offer optimized C-based alternatives for data-heavy operations.
What Python version should I use for Depth-First Search?
Use Python 3.10 or later for the best experience. Recent versions offer structural pattern matching, improved type hints, and performance improvements that benefit algorithm implementations.
When should I use DFS vs BFS?
Use DFS when you need to explore all paths, detect cycles, perform topological sorting, or solve backtracking problems. Use BFS when you need the shortest path in an unweighted graph or level-order traversal.
Is DFS guaranteed to find the shortest path?
No, DFS does not guarantee finding the shortest path. It finds a path if one exists, but it may not be the shortest. Use BFS for shortest paths in unweighted graphs or Dijkstra for weighted graphs.
How do I avoid infinite loops in DFS?
Maintain a visited set and only explore vertices that have not been visited. For directed graphs, you may also need a recursion stack set to detect back edges (cycles).
What is the difference between pre-order and post-order DFS?
Pre-order processes a vertex before its children (upon first visit). Post-order processes after all children are explored. Post-order is used in topological sort and SCC algorithms.
Can DFS be implemented iteratively?
Yes, using an explicit stack instead of recursion. This avoids stack overflow for deep graphs. The iterative version processes vertices in a slightly different order than recursive DFS for undirected graphs.
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.