DSA — Depth First Search
What is DFS?
Explores as far as possible along each branch before backtracking.
# Recursive
def dfs(graph, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# Iterative
def dfs_iterative(graph, start):
visited = set()
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
stack.append(neighbor)
Time Complexity
| Operation | Complexity |
|---|---|
| Visit all vertices | O(V + E) |
| Space | O(V) |
Applications
- Cycle detection
- Topological sorting
- Path finding
- Connected components
Mini Practice
- Implement recursive DFS
- Implement iterative DFS
- Detect cycles
- Find connected components
Up Next
Continue with Breadth First Search — BFS algorithm.
Related Topics
Frequently Asked Questions about Depth First Search
What is Depth First Search in DSA?
Depth First Search is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Depth First Search?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Depth First Search.
Why is Depth First Search important in DSA?
Depth First Search is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.