next up previous index
Next: The nature of weights Up: Shortest path methods Previous: Enumerations of shortest paths   Index


Efficiency

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.

Figure 13.4: The Dijkstra code modified for efficiency and storage allocation.
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;
}

This implies that nothing happens if the version and source are the same as before. When a new instance of a PositiveWeightedGraph is constructed, the local source and version variables are initialised appropriately. This code also shows how the work space is allocated. It is allocated the first time the dijkstra method is run, and is then only reallocated, if necessary, when the underlying graph is subsequently changed.


next up previous index
Next: The nature of weights Up: Shortest path methods Previous: Enumerations of shortest paths   Index
Peter Williams 2005-06-07