Algorithms Made Simple · 5 min read
Finding the quickest route and wiring everything together as cheaply as possible sound similar, but they are different problems with different algorithms.
Shortest path
If every edge counts the same, a breadth-first search finds the path with the fewest edges. When edges have different non-negative costs, Dijkstra’s algorithm does the job. It keeps the best known cost to every node, repeatedly settles the cheapest unsettled node using a priority queue, and updates its neighbors.
Dijkstra’s method relies on costs never being negative. With negative edges, you need an algorithm such as Bellman–Ford instead.
Guiding the search
The A* algorithm adds a heuristic, an estimate of the remaining distance, so the search leans toward the goal. If the estimate never overestimates the true remaining cost, A* still returns a shortest path and usually explores far fewer nodes.
Spanning tree
A spanning tree connects every node using exactly n − 1 edges and no loops. A minimum spanning tree does so with the least total weight. Kruskal’s method adds the cheapest edge that does not create a loop. Prim’s method grows one tree outward from a start node.
Do not mix them up
A minimum spanning tree minimizes the total cost of connecting everything. It does not promise that the route between two particular nodes is short. Use shortest paths for travel, and spanning trees for laying cable, pipes or roads.
