dlackovi2

Dijkstra algorithm

Jan 18th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.76 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Dijkstra {
  5.    private static final Graph.Edge[] GRAPH = {
  6.       new Graph.Edge("a", "b", 7),
  7.       new Graph.Edge("a", "c", 9),
  8.       new Graph.Edge("a", "f", 14),
  9.       new Graph.Edge("b", "c", 10),
  10.       new Graph.Edge("b", "d", 15),
  11.       new Graph.Edge("c", "d", 11),
  12.       new Graph.Edge("c", "f", 2),
  13.       new Graph.Edge("d", "e", 6),
  14.       new Graph.Edge("e", "f", 9),
  15.    };
  16.    private static final String START = "a";
  17.    private static final String END = "e";
  18.  
  19.    public static void main(String[] args) {
  20.       Graph g = new Graph(GRAPH);
  21.       g.dijkstra(START);
  22.       g.printPath(END);
  23.       //g.printAllPaths();
  24.    }
  25. }
  26.  
  27. class Graph {
  28.    private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges
  29.  
  30.    /** One edge of the graph (only used by Graph constructor) */
  31.    public static class Edge {
  32.       public final String v1, v2;
  33.       public final int dist;
  34.       public Edge(String v1, String v2, int dist) {
  35.          this.v1 = v1;
  36.          this.v2 = v2;
  37.          this.dist = dist;
  38.       }
  39.    }
  40.  
  41.    /** One vertex of the graph, complete with mappings to neighbouring vertices */
  42.   public static class Vertex implements Comparable<Vertex>{
  43.     public final String name;
  44.     public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
  45.     public Vertex previous = null;
  46.     public final Map<Vertex, Integer> neighbours = new HashMap<>();
  47.  
  48.     public Vertex(String name)
  49.     {
  50.         this.name = name;
  51.     }
  52.  
  53.     private void printPath()
  54.     {
  55.         if (this == this.previous)
  56.         {
  57.             System.out.printf("%s", this.name);
  58.         }
  59.         else if (this.previous == null)
  60.         {
  61.             System.out.printf("%s(unreached)", this.name);
  62.         }
  63.         else
  64.         {
  65.             this.previous.printPath();
  66.             System.out.printf(" -> %s(%d)", this.name, this.dist);
  67.         }
  68.     }
  69.  
  70.     public int compareTo(Vertex other)
  71.     {
  72.         if (dist == other.dist)
  73.             return name.compareTo(other.name);
  74.  
  75.         return Integer.compare(dist, other.dist);
  76.     }
  77.  
  78.     @Override public String toString()
  79.     {
  80.         return "(" + name + ", " + dist + ")";
  81.     }
  82. }
  83.  
  84.    /** Builds a graph from a set of edges */
  85.    public Graph(Edge[] edges) {
  86.       graph = new HashMap<>(edges.length);
  87.  
  88.       //one pass to find all vertices
  89.       for (Edge e : edges) {
  90.          if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
  91.          if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
  92.       }
  93.  
  94.       //another pass to set neighbouring vertices
  95.       for (Edge e : edges) {
  96.          graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
  97.          //graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
  98.       }
  99.    }
  100.  
  101.    /** Runs dijkstra using a specified source vertex */
  102.    public void dijkstra(String startName) {
  103.       if (!graph.containsKey(startName)) {
  104.          System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
  105.          return;
  106.       }
  107.       final Vertex source = graph.get(startName);
  108.       NavigableSet<Vertex> q = new TreeSet<>();
  109.  
  110.       // set-up vertices
  111.       for (Vertex v : graph.values()) {
  112.          v.previous = v == source ? source : null;
  113.          v.dist = v == source ? 0 : Integer.MAX_VALUE;
  114.          q.add(v);
  115.       }
  116.  
  117.       dijkstra(q);
  118.    }
  119.  
  120.    /** Implementation of dijkstra's algorithm using a binary heap. */
  121.    private void dijkstra(final NavigableSet<Vertex> q) {      
  122.       Vertex u, v;
  123.       while (!q.isEmpty()) {
  124.  
  125.          u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
  126.          if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
  127.  
  128.          //look at distances to each neighbour
  129.          for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
  130.             v = a.getKey(); //the neighbour in this iteration
  131.  
  132.             final int alternateDist = u.dist + a.getValue();
  133.             if (alternateDist < v.dist) { // shorter path to neighbour found
  134.                q.remove(v);
  135.                v.dist = alternateDist;
  136.                v.previous = u;
  137.                q.add(v);
  138.             }
  139.          }
  140.       }
  141.    }
  142.  
  143.    /** Prints a path from the source to the specified vertex */
  144.    public void printPath(String endName) {
  145.       if (!graph.containsKey(endName)) {
  146.          System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
  147.          return;
  148.       }
  149.  
  150.       graph.get(endName).printPath();
  151.       System.out.println();
  152.    }
  153.    /** Prints the path from the source to every vertex (output order is not guaranteed) */
  154.    public void printAllPaths() {
  155.       for (Vertex v : graph.values()) {
  156.          v.printPath();
  157.          System.out.println();
  158.       }
  159.    }
  160. }
Add Comment
Please, Sign In to add comment