The code I have is based on BFS and a little bit of Dijkstra and returns the shortest path of an unweighted directed graph as an integer. I was wondering if someone could take a look at my code too see if anything could be changed or improved:
public int bfsshortestpath (V source, V target) {
Map<V, Integer> dist = new TreeMap<V, Integer>();
Map<V, V> prev = new TreeMap<V, V>();
for(V v: adjlist.keySet()){
dist.put(v, null);
prev.put(v, null);
}
dist.put(source, 0);
Queue<V> q = new LinkedList<V>();
q.offer(source);
while(!q.isEmpty()){
V u = q.poll();
if(u == target)
break;
q.remove(u);
for(V neighbor: adjlist.get(u)){
int a = dist.get(u);
if(dist.get(neighbor) != null)
continue;
//BFS distance
dist.put(neighbor, a + 1);
prev.put(neighbor, u);
q.offer(neighbor);
}
}
List<V> s = new LinkedList<V>();
V u = target;
while(prev.get(u) != null){
s.add(u);
u = prev.get(u);
}
return s.size();
}