0
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.)

  • To make your code more of an [mre] please [edit] your post and add what is needed so we can copy-paste-run, including hard-coded test data that reproduces the problem. Also explain what output you expect. – c0der Dec 14 '21 at 05:23
  • You may find this [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) useful – c0der Dec 14 '21 at 05:25

0 Answers0