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
It is really no simpler to get the answer for just one pair than for all the pairs. The usual way to calculate a shortest path is to start like you do, but make a note whenever you encounter a new node and record the previous node on the path. Then, when you reach the target node, you can follow the backlinks to the source and get the path. So, remove the directions.add(current)
from the loop, and add code something like the following
Map backlinks = new HashMap();
in the beginning and then in the loop
if (!backlinks.containsKey(node)) {
backlinks.add(node, current);
q.add(node);
}
and then in the end, just construct the directions
list in backwards using the backlinks
map.