Graph Representation, BFS and DFS

Store graphs as adjacency lists or grids and use BFS and DFS for connected components, flood fill, cycle detection and bipartite checks.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Tree Problem Patterns

Graph problems are often hidden: a grid of land and water, a list of course prerequisites, or words that differ by one letter are all graphs.

Representation

  • Adjacency list for sparse graphs (the default). Adjacency matrix only for small, dense graphs.
  • Grids as implicit graphs: neighbours from direction arrays, no explicit edge list.
  • Directed vs undirected, weighted vs unweighted.

Traversals

  • DFS (recursive or stack): connected components, flood fill, cycle detection, path existence.
  • BFS (queue): shortest path in an unweighted graph, level-by-level spread.
  • Multi-source BFS: start from all sources at once (Rotting Oranges, 01 Matrix).
  • Always mark visited when you push, not when you pop, to avoid duplicates in the queue.

Common checks

  • Cycle in an undirected graph: DFS with parent, or DSU.
  • Cycle in a directed graph: DFS with a recursion-stack array, or Kahn's algorithm.
  • Bipartite: 2-colour with BFS or DFS (Is Graph Bipartite?).

Classic problems

Number of Islands, Flood Fill, Max Area of Island, Rotting Oranges, 01 Matrix, Surrounded Regions, Number of Enclaves, Clone Graph, Is Graph Bipartite?, Word Ladder, Number of Provinces.

Pitfalls

  • Recursion depth on a 1000 x 1000 grid. Use BFS or an iterative DFS.
  • Forgetting disconnected components: loop over every node as a start.

You are ready to move on when you can solve Rotting Oranges with multi-source BFS and explain why BFS finds shortest paths only in unweighted graphs.

Key concepts

  • Adjacency list vs matrix
  • Grids as graphs
  • DFS and connected components
  • BFS and unweighted shortest path
  • Multi-source BFS
  • Cycle detection
  • Bipartite check

Mini project

Solve these 10 in 7 days, log time and pattern: Flood Fill, Number of Islands, Number of Provinces, Max Area of Island, Rotting Oranges, 01 Matrix, Surrounded Regions, Clone Graph, Is Graph Bipartite?, Word Ladder.

Check yourself

Why should you mark a node visited when you push it into the BFS queue rather than when you pop it?

Free resources