Python Algorithms
Depth-First Search (DFS) in Python
Follow one path as deep as it goes before backing up. Write DFS with recursion in a few lines.
What you'll learn
- Recursive DFS
- The visited set
- How DFS order differs from BFS
DFS from A
A1stB2ndD3rd
C4thE5th
Go deep, then back up
Depth-first search follows one branch as far as possible before returning to explore another branch.
Key points
- Visit a node, then recursively visit each unvisited neighbour.
- The visited set stops cycles from looping forever.
- DFS reaches D before C, unlike BFS.
- It is useful for paths, cycle detection and topological sorting.
When should you use it?
- Practice problem solving and data structures.
- Process data when every algorithm step must be explicit.
- Prepare for programming exercises, exams, and interviews.
Depth-First Search in Python visualizer
O(V + E)Use Play or Step to follow each comparison and data movement.
Example code
main.py
graph = {"A": ["B", "C"], "B": ["D"], "C": ["E"], "D": [], "E": []}
def depth_first(node, visited=None):
visited = visited or set()
visited.add(node)
order = [node]
for neighbor in graph[node]:
if neighbor not in visited:
order.extend(depth_first(neighbor, visited))
return order
print(depth_first("A"))
Result of running the code
['A', 'B', 'D', 'C', 'E']
Code explanation
The visited set prevents repeated work and cycles. Recursive calls act as the traversal stack. Complexity is O(V + E).
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Count Islands Count groups of connected land cells in a grid. Medium
- Strongly Connected Components Count groups of nodes that can all reach each other. Hard
- Longest Path in a DAG Find the heaviest path in a task dependency graph. Hard