DSA — Graph Traversal
BFS (Breadth-First Search)
Explores all neighbors at current depth before moving deeper.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
DFS (Depth-First Search)
Explores as far as possible along each branch before backtracking.
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
BFS vs DFS
| Feature | BFS | DFS |
|---|---|---|
| Data Structure | Queue | Stack/Recursion |
| Approach | Level by level | Branch by branch |
| Use Case | Shortest path | Cycle detection |
Mini Practice
- Implement BFS
- Implement DFS
- Find shortest path with BFS
- Detect cycles with DFS
Up Next
Continue with BFS — breadth-first search in depth.
Related Topics
Frequently Asked Questions about Graph Traversal
What is Graph Traversal in DSA?
Graph Traversal 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 Graph Traversal?
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 Graph Traversal.
Why is Graph Traversal important in DSA?
Graph Traversal is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.