We have already discussed the fact that paths of shortest length may not be unique. Nonetheless it can be useful to have an enumeration of at least one. This is provided by the shortestPath method which returns an Enumeration as follows:
public Enumeration shortestPath(Object origin, Object destination) {
final Node source = (Node) nodeMap.lookup(origin);
final Node target = (Node) nodeMap.lookup(destination);
dijkstra(source);
if (!((WorkSpace) target.work).settled) {
throw new NoSuchElementException();
}
return new Enumeration() {
// use a stack to reverse the order
private Stack s = new StackArray();
private Node current = target;
{ // load the stack
while (current != source) {
s.push(current);
current = ((WorkSpace) current.work).previous;
}
s.push(source);
}
public boolean hasMoreElements() {
return !s.isEmpty();
}
public Object nextElement() {
if (!s.isEmpty()) {
return ((Node) s.pop()).label;
} else {
throw new NoSuchElementException();
}
}
};
}
This again throws a NoSuchElementException if there is no
path to the destination. Otherwise we use a
Stack
to reverse the order. It is more natural to enumerate the path from
origin to destination, whereas the information we have
available tells us the previous node on a path rather than the next
node. We start by pushing the current = target node onto the
stack and then follow with the previous node, and so on until we
reach the source node. This has no previous node, so finally we
push the source onto the stack.