Алгоритм Дейкстры печатает последний путь предшественника вместо кратчайшего - PullRequest
1 голос
/ 02 марта 2020

В настоящее время моя функция печати печатает путь к последним посещенным узлам к месту назначения вместо кратчайшего пути. Например, если кратчайший путь - это a, c, e с a = 1 c = 1, e = 4, а другой путь - это a, d, e с весами a = 1, d = 4, e = 4, мой алгоритм движется в этом направлении: a, c, d, e, но будет печатать ade, так как они были посещены недавно, и мой метод setPredecessor () установлен для плохого предшественника. Любые идеи по этому поводу были бы очень благодарны, либо чтобы исправить мой текущий код, либо попытаться сделать это по-другому.

class ShortestPathFinder {
        private  Graph graph = new Graph();
        private  Vertex source = new Vertex(0, null);
        private Vertex destination = new Vertex(0,null);
        private  Map<Vertex,Vertex> previousVertex = new HashMap();

    public void  findShortestPath(Graph graph, Vertex source, Vertex destination, ReadInput graphReader) {
        this.destination = destination;
        this.source = source;

        source.setDistanceFromSource(0);
        PriorityQueue<Vertex> priorityQueue = new PriorityQueue<>();
        priorityQueue.add(source);
        source.setVisited(true);
        boolean destinationFound = false;

        while( !priorityQueue.isEmpty() && destinationFound == false){
            // Getting the minimum distance vertex from priority queue
            Vertex actualVertex = priorityQueue.poll();
            System.out.println("working on: " + actualVertex.getID());

            actualVertex = graphReader.SetAdjList(actualVertex);


            for(Edge edge : actualVertex.getAdjacenciesList()){
                Vertex v = edge.getTargetVertex();
                System.out.println("a Neighbor is: " + v.getID());
                if(!v.isVisited()) {
                    if(v.getID() == destination.getID() || edge.getStartVertex().getID() == destination.getID()) {
                        System.out.println("Destination found");
                            destination.setPredecessor(actualVertex);
                            destination.setDistanceFromSource(actualVertex.getDistanceFromSource() + edge.getWeight());
                            destinationFound = true;
                            break;  
                    }
                    double newDistance = actualVertex.getDistanceFromSource() + edge.getWeight();

                    if( newDistance < v.getDistanceFromSource() ){
                        priorityQueue.remove(v);
                        v.setDistanceFromSource(newDistance);
                        v.setPredecessor(actualVertex);
                        priorityQueue.add(v);
                        System.out.println("Added: " + v.getID());
                    }
                }
            }
            actualVertex.setVisited(true);
        }       
    }

    public List<Vertex> getPath() {
        List<Vertex> path = new ArrayList<>();
        for(Vertex vertex=destination;vertex!=null;vertex=vertex.getPredecessor()){
                path.add(vertex);
        }
        Collections.reverse(path);
        return path;
    }       
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...