Graph Search & Decomposition

graph exploration as a design tool

Many problems that do not look like graphs become easy the moment you draw them as one and walk through it systematically. Can you get from this airport to that one? Is this maze solvable? Which web pages can a crawler reach from the homepage? Each is really a question about a graph, and the answer falls out of a single disciplined walk that touches every reachable piece exactly once. Graph exploration is the idea that this one walk — done as breadth-first or depth-first search — is a reusable engine you bolt small jobs onto.

The shared skeleton is simple: keep a set of already-visited vertices, start at some source, and repeatedly take an unexplored vertex, mark it visited, and queue up its not-yet-visited neighbours. BFS does this with a queue, so it fans out in rings of increasing distance; DFS does it with a stack (or recursion), so it plunges down one path as far as it can before backing up. Because each marks every vertex once and inspects every edge once, both run in O(n + m) on an adjacency list. The power is that you do not change the walk — you just hang a small action at the right moment: count how many separate walks it took to cover everything (connected components), record each vertex's distance from the source (shortest paths in edges), colour vertices alternately to test two-sidedness (bipartiteness), note the order vertices finish (topological sort), or watch for an edge back to an ancestor (cycle detection).

This is why graph search is treated as a design paradigm and not just two procedures. Once you can see your problem as 'reach everything from here and observe something as I go', you inherit a correct, linear-time traversal for free and only have to design the small observation. The honest limits: exploration answers reachability and structure (what connects to what, in how many hops, in what order), but plain BFS and DFS ignore edge weights — for cheapest paths under varying costs you need the weighted machinery of Dijkstra or Bellman-Ford, and for capacity questions you need flow. Knowing which questions a bare traversal can and cannot answer is half of using it well.

A maze is a graph: cells are vertices, open passages are edges. Run BFS from the entrance and stop when you pop the exit — the BFS rings give you not just 'is it solvable?' but the fewest-step path. Swap in DFS and you instead get one full path that wanders deep; swap in a component count and you learn how many disconnected rooms exist.

One traversal, many answers: you reuse the same walk and only change the small thing you record along the way.

A bare traversal answers reachability and hop-count, not cheapest-cost. The moment edges carry differing weights, BFS's 'fewest edges' stops meaning 'cheapest' and you must move to weighted shortest-path algorithms.

Also called
traversal-based design以走訪為基礎的設計