</>
Skip to content
DSA lessons (26/55)

DSA — BFS

What is BFS?

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()
        process(vertex)
        
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

BFS for Shortest Path

def bfs_shortest_path(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

OperationComplexity
Visit all verticesO(V + E)
SpaceO(V)

Use Cases

  • Finding shortest path
  • Level-order traversal
  • Social network connections
  • Web crawling

Mini Practice

  1. Implement BFS traversal
  2. Find shortest path
  3. Level-order tree traversal
  4. Check if graph is connected

Up Next

Continue with DFS — depth-first search in depth.

Related Topics

Frequently Asked Questions about BFS

What is BFS in DSA?

BFS 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 BFS?

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 BFS.

Why is BFS important in DSA?

BFS is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.