da2423 :
나는 익스트라의 알고리즘을 인쇄하려고 시도하고 있지만, 현재는 대상 ID는 내 getPath () 메소드에서 인쇄된다. 내 생각은 시작 정점이 인쇄 될 때까지, 대상 정점에서 거꾸로 작동하고 각 전임자를 인쇄하는 것이었다. 가게에 다른 방법이 있다면 / 나는 그것을 다른 방식을 시도하는 오픈보다 더 많은 것 경로를 인쇄, 나는 어떤 아이디어를 주셔서 감사합니다!
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();
private Set<Vertex> visited = new HashSet();
public Optional<Path> findShortestPath(Graph graph, Vertex source, Vertex destination, ReadInput graphReader) {
this.destination = destination;
this.source = source;
Optional<Path> pathFound = Optional.empty();
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()) {
System.out.println("Destination found");
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
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);
}
return pathFound;
}
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;
}
}
Arham 시디키 :
목적지에 도달했을 때 코드의 다음 부분이라고합니다 :
if(v.getID() == destination.getID()) {
System.out.println("Destination found");
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
destinationFound = true;
break;
}
즉, 각각의 V는 당신의 것입니다 그것의 전임자 세트가 결코 getPath()
방법에 따라 달라집니다. 등의 경우 문에서 설정을 고려 :
if(v.getID() == destination.getID()) {
System.out.println("Destination found");
destination.setPredecessor(actualVertex); // sets the predecessor for backwards traversal
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
destinationFound = true;
break;
}