Graphs: BFS, DFS & friends

Adjacency representations, topological sort, union-find with path compression, Dijkstra. Grid problems are graphs in disguise — say so out loud.

About 30 min read3-question knowledge check

The mental model

A graph is a map of cities and roads. Cities are nodes (vertices), roads are edges. Some roads are one-way (a directed graph), some two-way (undirected). Some roads have a length or a toll (a weighted graph). That is the entire vocabulary, and almost every "connection" problem in computing is secretly this map: friends on a social network, packages depending on other packages, web pages linking to pages, tasks that must precede other tasks, cells in a grid that are neighbours. The skill is *hearing the map inside the problem* — and the roadmap says it plainly: grid problems are graphs in disguise; say so out loud. A 2-D grid is a graph where each cell is a node connected to its four (or eight) neighbours; once you see that, the maze, the island count, and the rotting-oranges problem are all the same two algorithms.

The two ways to explore that map are the whole subject. Breadth-first search (BFS) is a *ripple in a pond*: from the start, visit everything one road away, then everything two roads away, then three — expanding in concentric rings. Because it reaches nodes in order of distance, BFS finds the shortest path in an unweighted graph. Depth-first search (DFS) is a thread through a maze: pick a direction, follow it as far as it goes, hit a dead end, back up, try the next. DFS naturally explores whole branches to the bottom first, which makes it the tool for "does a path exist", cycle detection, topological ordering, and anything with a recursive substructure.

Why do these exist? Because "reachability and distance over connections" is one of the most common problem shapes in all of software, and these two traversals are the primitives everything else is built from. Shortest routes, dependency resolution, deadlock detection, network flow, and most grid puzzles are BFS or DFS with a twist. The interview payoff is enormous leverage: master two traversal skeletons and a handful of add-ons (a visited set, a distance array, a topological order, union-find) and you can attack a large fraction of the "hard" round. The one idea to carry through: BFS = queue = shortest path in unweighted graphs; DFS = stack/recursion = reachability, cycles, and ordering — and the moment edges have weights, you need Dijkstra, not plain BFS.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision