/* * Methode to calculate a weight for a way to the start point , it can be * one edge or a couple of edges */ private static int calculateWeightOfWay(Vertex firstVertex, Vertex secondVertex) { int currentWeight = (Integer) verticesMap.get(firstVertex.getId()).get(1); ArrayList<Edge<Vertex>> edgesOfFirstVertex = (ArrayList<Edge<Vertex>>) graph.getIncidentEdges(firstVertex.getId()); for (Edge<Vertex> e : edgesOfFirstVertex) { if (e.getVertexB().getId() == secondVertex.getId()) { int edgeWeightBetweenFirstandSecond = e.getWeight(); return edgeWeightBetweenFirstandSecond + currentWeight; } } System.out.println("no edge weight found"); return 0; }
/** * performs the Dijkstra algorithm * * @param graph a graph, in which the Dijkstra will be performed * @param queue a queue of vertices to help perform Dijkstra * @param startVertexID a start vertices id * @param destinationVertexID an end vertices id */ private static void performeDijkstra( Graph<Vertex, Edge<Vertex>> graph, ArrayList<Vertex> queue, int startVertexID, int destinationVertexID) { while (queue.size() != 0) { int lowest = 0; for (int i = 0; i < queue.size(); i++) { if (queue.get(i).getDistance() < queue.get(lowest).getDistance()) { lowest = i; } } Vertex lowestElementInQueue = queue.get(lowest); // stop the loop if the destination is reached if (lowestElementInQueue.getId() == destinationVertexID) break; queue.remove(lowestElementInQueue); Collection<Edge<Vertex>> edgesOfFirstVertex = graph.getIncidentEdges(lowestElementInQueue); if (edgesOfFirstVertex.size() != 0) { for (Edge<Vertex> edge : edgesOfFirstVertex) { Vertex neighbour = edge.getVertexB(); int weightOfEdge = edge.getWeight(); if (weightOfEdge < 0) { throw new IllegalArgumentException( "one edge of " + lowestElementInQueue.getId() + " is negative"); } relax(lowestElementInQueue, neighbour, weightOfEdge); } } } ResultsDisplay.printResults(graph); ResultsDisplay.printTheShortestWay(graph, startVertexID, destinationVertexID); }