solved s07 ex04

This commit is contained in:
navid.sassan 2020-11-08 20:54:05 +01:00
parent cc51b4d33b
commit a828de13ce
2 changed files with 46 additions and 3 deletions

View File

@ -30,7 +30,6 @@ class DijkstraNode<E> extends Node<E> implements Comparable<DijkstraNode> {
} }
public int compareTo(DijkstraNode n) { public int compareTo(DijkstraNode n) {
// TODO: implement return Double.compare(this.dist, n.getDist());
return 0;
} }
} }

View File

@ -1,17 +1,23 @@
package ch.zhaw.ads; package ch.zhaw.ads;
import java.util.Scanner; import java.util.Scanner;
import java.util.Queue;
import java.util.PriorityQueue;
public class RouteServer implements CommandExecutor { public class RouteServer implements CommandExecutor {
Graph<DijkstraNode, Edge> graph;
@Override @Override
public String execute(String command) { public String execute(String command) {
Graph<DijkstraNode, Edge> graph = this.readInput(command); graph = this.readInput(command);
StringBuffer result = new StringBuffer(100); StringBuffer result = new StringBuffer(100);
for (Node node : graph.getNodes()) { for (Node node : graph.getNodes()) {
result.append(node.getName() + "\n"); result.append(node.getName() + "\n");
} }
result.append("\"\n"); result.append("\"\n");
this.dijkstra("Winterthur", "Lugano");
return result.toString(); return result.toString();
} }
@ -37,4 +43,42 @@ public class RouteServer implements CommandExecutor {
scanner.close(); scanner.close();
return graph; return graph;
} }
private void dijkstra(String from, String to) {
Queue<DijkstraNode> pq = new PriorityQueue<DijkstraNode>();
DijkstraNode<Edge> start = graph.findNode(from);
DijkstraNode<Edge> goal = graph.findNode(to);
start.setDist(0);
pq.add(start);
while (!pq.isEmpty()) {
DijkstraNode<Edge> current = pq.poll();
current.setMark(true);
// implement equals for this
// if (current.equal(goal)) {
if (current.getName() == to) {
break;
}
for (Edge<DijkstraNode> edge : current.getEdges()) {
DijkstraNode<Edge> sucessor = edge.getDest();
if (!sucessor.getMark()) {
double dist = edge.getWeight() + current.getDist();
if (sucessor.getPrev() == null || dist < sucessor.getDist()) {
sucessor.setDist(dist);
sucessor.setPrev(current);
pq.add(sucessor);
}
}
}
}
System.out.println("\n\nShortest path:\n");
// print the shortest path
DijkstraNode<Edge> current = goal;
while (current.getPrev() != null) {
System.out.println(current.getName());
current = current.getPrev();
}
System.out.println(current.getName());
System.out.println("\n\n");
}
} }