public void shortestPath(String searched,String destination) {
Queue <Vertex> queue=new LinkedList<>();
Stack <Vertex> path=new Stack<>();
Vertex root=vertices.get(searched);
Vertex end=vertices.get(destination);
queue.add(root);
root.setVisited(true);
while(!queue.isEmpty())
{
Vertex current=queue.poll();
Vertex[] neighbors=getNeighbor(current);
for(int i=0;i<neighbors.length;i++)
{
if(!neighbors[i].getVisited())
{
queue.add(neighbors[i]);
neighbors[i].setVisited(true);
neighbors[i].setPrevious(current);
if(neighbors[i]==end)
{
queue.clear();
break;
}
}
}
}
while(end!=null)
{
path.add(end);
end.setVisited(false);
end=end.getPrevious();
}
while(!path.isEmpty())
{
System.out.print(path.pop().getName()+" ");
}
System.out.println();
}
I tried to write shortest path algorithm for unweighted and undirected graph. Algorithm works for some cases, but in other cases stucks in while(end!=null) part and loops infinitely. I can't find the mistake I made in the code.(vertices is hashmap and vertex is a class which I created.)