Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. public class Roadmap extends Graph {
  2.  
  3.     // Determines and prints the shortest path from station "from" to station "to" (-> vertex array indices). The shortest distance is returned.
  4.     public int printShortestDistance(int from, int to) {
  5.         return dijkstra(from, to)[to];
  6.     }
  7.  
  8.  
  9.     // Determines the shortest paths from station "from" (-> vertex array index) to all stations and returns them in an array.
  10.     public int[] printShortestDistances(int from) {
  11.         return dijkstra(from, vCount - 1);
  12.     }
  13.  
  14.  
  15.     private int[] dijkstra(int from, int to) {
  16.         boolean[] visited = new boolean[vCount];
  17.         int[] distance = new int[vCount];
  18.         StringBuilder sb = new StringBuilder();
  19.  
  20.         for (int i = 0; i < vCount; i++) {
  21.             distance[i] = Integer.MAX_VALUE;
  22.             visited[i] = false;
  23.         }
  24.         distance[from] = 0;
  25.  
  26.         for (int i = 0; i < vCount - 1; i++) {
  27.             int min = Integer.MAX_VALUE;
  28.             int min_index = -1;
  29.             for (int j = 0; j < vCount; j++) {
  30.                 if (!visited[j] && distance[j] <= min) {
  31.                     min = distance[j];
  32.                     min_index = j;
  33.                 }
  34.             }
  35.             visited[min_index] = true;
  36.  
  37.             for (int j = 0; j < vCount; j++) {
  38.                 if (!visited[j] && getWeight(min_index, j) != 0 && distance[min_index] + getWeight(min_index, j) < distance[j]) {
  39.                     distance[j] = distance[min_index] + getWeight(min_index, j);
  40.                     sb.append("\n over ").append(vertices[j].toString()).append(" ").append(distance[j]);
  41.                 }
  42.             }
  43.         }
  44.  
  45.         for (int j = 0; j < vCount; j++) {
  46.             if (distance[j] == Integer.MAX_VALUE) {
  47.                 distance[j] = -1;
  48.             }
  49.         }
  50.         System.out.print("Shortest distance from " + vertices[from] + " to " + vertices[to] + " is: " + distance[to]);
  51.         System.out.println(sb.toString());
  52.         return distance;
  53.     }
  54.  
  55.     private int getWeight(int v1, int v2) {
  56.         for (int i = 0; i < eCount; i++) {
  57.             if (edges[i].in == v1 && edges[i].out == v2 || edges[i].in == v2 && edges[i].out == v1)
  58.                 return edges[i].weight;
  59.         }
  60.         return 0;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement