Several algorithms are described for tracing the shortest path for a simple, positively weighted, connected graph. This is a simpler problem than the traveling salesman problem, and we might hope that a solution algorithm is available.
In addition, algorithms for finding a minimal spanning tree are also described, which are useful for trimming a graph to a subgraph which leaves all nodes connected, but eliminates ``unnecessary'' connections.
Notice that several of the algorithms we study in this section are actually found in the exercise portion of the section.
How might you find the shortest path between two nodes? Some suggestions might include
It is relatively easy to come up with algorithms to solve this problem, but of course some ways are better than others. We'll look at a couple of standard algorithms for carrying out this task.
This algorithm was first described by Edsger W. Dijkstra. Here is a web-based example of the workings of the algorithm (where there is no stated destination node).
We keep track of two arrays, indexed by the nodes of graph G:
Let's look at an example:
Exercise #3, p. 437/441
The Bellman-Ford Algorithm (AnotherShortestPath, p. 438/442) operates in a fashion similar to Dijkstra's algorithm, only it finds the shortest distance from x to every other node as described in the book (one could add a termination step, of course).
Each node keeps an eye on its adjacent nodes:
Exercise #10/12, p. 439/443
Floyd's algorithm (the algorithm AllPairsShortestPath, p. 439/444) is simpler, stupider, but has the advantage that it produces the shortest distance between any two nodes in the graph. Sometimes this is desired, rather than the distance between any special pair. It too works with the adjacency matrix representation of the graph (modified to contain off the diagonal).
It simply uses brute force to compare direct paths between a pair and indirect paths between the same pair: we compare
to A(i,j), to see if it's shorter to go from i to j via k.
Exercise #13/15, p. 439/444.
Definition: A spanning tree for a connected graph G is a non-rooted tree containing the nodes of the graph and a subset of the arcs of G. A minimal spanning tree is a spanning tree of least weight of a simple, weighted, connected graph G.
Prim's algorithm is a simple one for constructing a minimal spanning tree (these may not be unique!):
Exercise #18/20, p. 440/445.
Kruskal's algorithm is an alternative method for generating a minimal spanning tree. It works by building up a spanning tree from the arcs, ordered from smallest in weight to largest. The only reason to reject a smaller arc over a larger is if it creates a cycle.
Exercise #21/23, p. 441/445.