|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Dijkstra's Algorithm |
| 5 | + * Find the shortest weighted path from some starting vertex to all vertices. |
| 6 | + * Edges have non-negative weight |
| 7 | + * |
| 8 | + * Tags: Graph |
| 9 | + */ |
| 10 | +class Dijkstra { |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * Create a wrapper class for edge |
| 18 | + */ |
| 19 | + class Path implements Comparable<Path> { |
| 20 | + Vertex dest; |
| 21 | + double cost; |
| 22 | + |
| 23 | + public Path(Vertex d, double c) { |
| 24 | + dest = d; |
| 25 | + cost = c; |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public int compareTo(Path rhs) { |
| 30 | + double otherCost = rhs.cost; |
| 31 | + return cost < otherCost ? -1 : cost > otherCost ? 1 : 0; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + HashMap<String, Vertex> vertexMap = new HashMap<String, Vertex>(); |
| 36 | + |
| 37 | + public void dijkstra(String startName) { |
| 38 | + PriorityQueue<Path> pq = new PriorityQueue<Path>(); |
| 39 | + Vertex start = vertexMap.get(startName); |
| 40 | + if (start == null) |
| 41 | + throw new NoSuchElementException("Start vertex not found"); |
| 42 | + |
| 43 | + pq.add(new Path(start, 0)); |
| 44 | + start.dist = 0; |
| 45 | + |
| 46 | + int nodesSeen = 0; |
| 47 | + while (!pq.isEmpty() && nodesSeen < vertexMap.size()) { |
| 48 | + Path vrec = pq.remove(); |
| 49 | + Vertex v = vrec.dest; |
| 50 | + if (v.visited != 0) // skip visited |
| 51 | + continue; |
| 52 | + |
| 53 | + v.visited = 1; // set visited |
| 54 | + nodesSeen++; |
| 55 | + |
| 56 | + for (Edge e : v.adj) { |
| 57 | + Vertex w = e.dest; |
| 58 | + double cvw = e.cost; // cost between v and w |
| 59 | + if (cvw < 0) { |
| 60 | + // throw new GraphException("Graph has negative edges"); |
| 61 | + } |
| 62 | + |
| 63 | + if (w.dist > v.dist + cvw) { |
| 64 | + w.dist = v.dist + cvw; |
| 65 | + w.prev = v; // set previous Vertex |
| 66 | + pq.add(new Path(w, w.dist)); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + class Vertex { |
| 73 | + int visited; |
| 74 | + Vertex prev; |
| 75 | + double dist; |
| 76 | + List<Edge> adj; |
| 77 | + } |
| 78 | + |
| 79 | + class Edge { |
| 80 | + Vertex dest; |
| 81 | + double cost; |
| 82 | + } |
| 83 | +} |
0 commit comments