🔗

Graph Traversal (BFS / DFS)

Visit every node using depth-first or breadth-first strategies.

0 Problems3-4 hours

Overview

Graph traversal visits every reachable node exactly once. DFS goes as deep as possible before backtracking — implemented recursively or with an explicit stack. BFS visits all neighbors at the current depth before going deeper — uses a queue. Both run in O(V+E).

Complexity Summary

Time Complexity

O(V + E)

Space Complexity

O(V) for visited + recursion/queue

Key Patterns & Techniques

Learn the core patterns in this topic. Each block explains when to use the pattern, the intuition behind it, and a compact code example.

1

DFS

Concept

go deep, backtrack, use recursion or stack; finds paths and cycles

Practice questions for this pattern
2

BFS

Concept

level by level with a queue; finds shortest path in unweighted graph

Practice questions for this pattern
3

Visited set

Concept

essential to avoid infinite loops in cyclic graphs

Practice questions for this pattern
4

Connected components

Concept

run DFS/BFS from every unvisited node

Practice questions for this pattern
5

Bipartite check

Concept

2-color with BFS; odd cycle means not bipartite

Practice questions for this pattern
6

Flood fill

Concept

BFS/DFS on a 2D grid from a starting cell

Practice questions for this pattern
DSA Practice Online - 150+ Coding Interview Questions | LeetCode Alternative | InstaMock - AI Mock Interview