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

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

FeatureBFSDFS
Data StructureQueueStack/Recursion
ApproachLevel by levelBranch by branch
Use CaseShortest pathCycle detection

Mini Practice

  1. Implement BFS
  2. Implement DFS
  3. Find shortest path with BFS
  4. 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.