Several algorithms are described for tracing the shortest path for a simple, positively weighted, connected graph. 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.
Last class I asked you to consider your own intuitive schemes for finding the shortest path between two nodes. Some suggestions included
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
The Bellman-Ford Algorithm (AnotherShortestPath, p. 438) 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, p. 439
Floyd's algorithm (the algorithm AllPairsShortestPath, p. 439) 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 (homework problem), p. 439.
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, p. 440.
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:
Exercise #21, p. 441.