Traverse complex networks using BFS, DFS, and Dijkstra's shortest path algorithms.
4 algorithms1 variant2 races7 problems
4 algorithms. Each one builds on the last.
Cheapest path to every node when no edge costs less than zero.
O((V + E) log V) time · O(V + E) spaceSlower than Dijkstra, but it copes with negative edges.
O(V · E) time · O(V) spaceVisualizeDijkstra and A* race across a real city. A* aims at the destination and explores far fewer roads.
O((V + E) log V) time · O(V) spaceVisualizeSame input, side by side. Watch who wins.
A graph is a set of nodes joined by edges, with no root and no fixed shape, so a search must remember which nodes it has already seen or it will go round a loop forever. These pages cover the two ways to explore a graph and the two classic ways to find the cheapest route through one, then run them on real streets. They appear in route planners, network routing and interviews alike.
Each page grows a set of reached nodes outward from one source and records, for every node, the node it was reached from. Following those parent links back from the target gives the route. What changes is the rule for which node to handle next: the oldest one waiting (a queue), the newest (a stack), the cheapest found so far (a priority queue), or every edge again in fixed passes.
First check whether edges have different costs. If they all count the same, BFS gives the shortest route and DFS covers reachability. If costs differ, look for negative weights: none means Dijkstra, any means Bellman-Ford. The usual mistake is running Dijkstra with a negative edge, where it can finish a node too early and report a wrong cost without any warning.