You will see that the basic dijkstra method is called by each of these routines. But if the graph and the source node has not changed since the last call, all the necessary results are already stored in the WorkSpace attached to each node. For example, you might want to keep the origin fixed but vary the destination. There is no need to run the costly dijkstra method again.
For efficiency therefore, we keep a record of the source for which the method was last called, and also of the version of the graph when it was last called. The latter is provided by the protected version instance variable of the WeightedGraph class. Therefore the actual code is as shown in Figure 13.4.
public PositiveWeightedGraph() {
source = null;
version = super.version - 1;
}
private void dijkstra(Node origin) {
// don't run if nothing has changed
if (version == super.version && origin == source) {
return;
}
// allocate new work space if necessary
if (version != super.version) {
Iterator i = nodeMap.iterator();
while (i.hasNext()) {
Node n = (Node) ((LookupTable.Entry) i.next()).value();
if (n.work == null) {
n.work = new WorkSpace();
}
}
}
.... code from Figure 3
version = super.version;
source = origin;
}
|