I\'m trying build a method which returns the shortest path from one node to another in an unweighted graph. I considered the use of Dijkstra\'s but this seems a bit overkil
Thank you Giolekva!
I rewrote it, refactoring some:
public List getDirections(Node sourceNode, Node destinationNode) {
//Initialization.
Map nextNodeMap = new HashMap();
Node currentNode = sourceNode;
//Queue
Queue queue = new LinkedList();
queue.add(currentNode);
/*
* The set of visited nodes doesn't have to be a Map, and, since order
* is not important, an ordered collection is not needed. HashSet is
* fast for add and lookup, if configured properly.
*/
Set visitedNodes = new HashSet();
visitedNodes.add(currentNode);
//Search.
while (!queue.isEmpty()) {
currentNode = queue.remove();
if (currentNode.equals(destinationNode)) {
break;
} else {
for (Node nextNode : getChildNodes(currentNode)) {
if (!visitedNodes.contains(nextNode)) {
queue.add(nextNode);
visitedNodes.add(nextNode);
//Look up of next node instead of previous.
nextNodeMap.put(currentNode, nextNode);
}
}
}
}
//If all nodes are explored and the destination node hasn't been found.
if (!currentNode.equals(destinationNode)) {
throw new RuntimeException("No feasible path.");
}
//Reconstruct path. No need to reverse.
List directions = new LinkedList();
for (Node node = sourceNode; node != null; node = nextNodeMap.get(node)) {
directions.add(node);
}
return directions;
}