DSA — Breadth First Search
What is BFS?
Explores all vertices at the present depth before moving to vertices at the next depth level.
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)
Shortest Path
def bfs_shortest(graph, start, target):
visited = set()
queue = deque([(start, [start])])
visited.add(start)
while queue:
vertex, path = queue.popleft()
if vertex == target:
return path
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, path + [neighbor]))
return None
Time Complexity
| Operation | Complexity |
|---|---|
| Visit all vertices | O(V + E) |
| Space | O(V) |
Applications
- Shortest path in unweighted graph
- Level-order traversal
- Social network connections
- Web crawling
Mini Practice
- Implement BFS
- Find shortest path
- Level-order tree traversal
- Check bipartite graph
Up Next
Continue with Dijkstra's Algorithm — weighted shortest path.
Related Topics
Frequently Asked Questions about Breadth First Search
What is Breadth First Search in DSA?
Breadth 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 Breadth 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 Breadth First Search.
Why is Breadth First Search important in DSA?
Breadth First Search is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.