From 53756b586c3e42186ca1c7744cf3231a99f815d7 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Tue, 1 Nov 2022 21:01:15 +0100 Subject: [PATCH] Implement Dijkstras algorithm --- .../java/ch/nuth/zhaw/exbox/RouteServer.java | 70 ++++++++++++++++--- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java b/app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java index 13e541c..2e9db70 100644 --- a/app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java +++ b/app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java @@ -2,27 +2,75 @@ package ch.nuth.zhaw.exbox; import java.util.LinkedList; import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; public class RouteServer implements CommandExecutor { /** - build the graph given a text file with the topology - */ + * build the graph given a text file with the topology + */ public Graph createGraph(String topo) throws Exception { // TODO implement + Graph graph = new AdjListGraph<>(DijkstraNode.class, Edge.class); + + for (String line : topo.split("\r?\n")) { + String[] attributes = line.split(" "); + + try { + for (int i = 0; i <= 1; i++) { + graph.addEdge(attributes[i], attributes[1 - i], Double.parseDouble(attributes[2])); + } + } catch (Throwable e) { + throw new Exception(e); + } + } + + return graph; } - /** - apply the dijkstra algorithm - */ + * apply the dijkstra algorithm + */ public void dijkstraRoute(Graph graph, String from, String to) { - // TODO implement + Queue pendingNodes = new PriorityQueue<>(); + DijkstraNode start = graph.findNode(from); + DijkstraNode end = graph.findNode(to); + start.setDist(0); + pendingNodes.add(start); + + while (!pendingNodes.isEmpty()) { + DijkstraNode current = pendingNodes.poll(); + current.setMark(true); + + if (current == end) { + return; + } + + for (Edge edge : current.getEdges()) { + if (edge.getDest() instanceof DijkstraNode node && + !node.getMark()) { + double dist = current.getDist() + edge.getWeight(); + + if (!pendingNodes.contains(node) || + dist < node.getDist()) { + node.setDist(dist); + node.setPrev(current); + + if (pendingNodes.contains(node)) { + pendingNodes.remove(node); + } + + pendingNodes.add(node); + } + } + } + } } /** - find the route in the graph after applied dijkstra - the route should be returned with the start town first - */ + * find the route in the graph after applied dijkstra + * the route should be returned with the start town first + */ public List getRoute(Graph graph, String to) { List route = new LinkedList<>(); DijkstraNode town = graph.findNode(to); @@ -39,7 +87,9 @@ public class RouteServer implements CommandExecutor { List route = getRoute(graph, "Lugano"); // generate result string StringBuilder builder = new StringBuilder(); - for (DijkstraNode rt : route) builder.append(rt).append("\n"); + for (DijkstraNode rt : route) { + builder.append(rt).append("\n"); + } return builder.toString(); } }