All Topics

Graphs

BFS, DFS, shortest paths, topological sort, union-find, and advanced graph algorithms

0/65 solved

BFS & DFS

Foundation of graph traversal — explore level-by-level or depth-first

O(V + E) O(V)

Approach

BFS: Use a queue for level-by-level exploration — ideal for shortest paths. DFS: Use recursion or stack for deep exploration — ideal for connected components, cycle detection, and path finding.

How to Recognize

1

Problem involves traversing a grid or adjacency list

2

Need to find connected components or reachability

3

Phrases like 'number of islands', 'flood fill', 'surrounded regions'

4

Shortest path in unweighted graph → BFS

Pro Tips

BFS guarantees shortest path in unweighted graphs

Use visited set to avoid infinite loops in cyclic graphs

For grids, directions array simplifies neighbor traversal: {{0,1},{0,-1},{1,0},{-1,0}}

9

Total

1

Easy

7

Medium

1

Hard

Time

O(V + E)

Space

O(V)