Traversal and shortest paths: how to walk a graph, and how to choose which traversal fits the question.
Graph search algorithms differ mainly in the data structure that holds the frontier — the set of discovered but not yet expanded vertices. Breadth-first search uses a FIFO queue, so vertices are expanded in order of hop count; it finds shortest paths when every edge has the same cost. Depth-first search uses a stack (often the recursion stack), so it follows one branch as far as possible before backtracking; it is the basis of cycle detection, topological sorting and connected components. Dijkstra's algorithm uses a priority queue keyed by tentative distance, so it expands vertices in order of total path weight and finds shortest paths when edge weights are non-negative.
| Problem | Algorithm | Time |
|---|---|---|
| Fewest hops, unweighted shortest path | BFS | O(V + E) |
| Reachability, cycles, topological order | DFS | O(V + E) |
| Shortest path, non-negative weights | Dijkstra | O((V + E) log V) |
| Negative edge weights | Bellman-Ford | O(V E) |
The BFS vs DFS vs Dijkstra page runs all three on the same graph side by side. A useful mental model: Dijkstra with every edge weight equal to one behaves like BFS, and BFS with the queue replaced by a stack becomes an iterative DFS. Choosing correctly is mostly about the edge weights and whether you need distances or only structure. For dense graphs with many queries, all-pairs algorithms such as Floyd-Warshall become competitive, and A* adds a heuristic to Dijkstra when a good distance estimate to the goal exists.