← Coding Interview Prep (LeetCode) learning path
Coding Interview Prep (LeetCode) · Module 8 of 10

Graphs: BFS and DFS

Graphs model connections; BFS and DFS explore them.

📖 Key ideas

  1. Represent graphs with adjacency lists.
  2. BFS explores level by level and finds the shortest path in unweighted graphs.
  3. DFS goes deep first, using recursion or a stack.
  4. Grid problems (islands, flood fill) are graphs of cells.
  5. Track visited nodes to avoid infinite loops.
💡 Real-life example: BFS is ripples spreading in a pond; DFS is exploring one cave tunnel to its end before trying the next.
Adjacency listEach node lists its neighbours
BFSBreadth-first search, level by level
DFSDepth-first search, go deep first
Visited setNodes already explored