Skip to content

Commit c9d0aa1

Browse files
rmakynenrmakynen
rmakynen
authored and
rmakynen
committed
New Dijkstra's algorithm with better comments.
1 parent d2d0b78 commit c9d0aa1

File tree

1 file changed

+178
-0
lines changed

1 file changed

+178
-0
lines changed

Others/Dijkstra.java

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
package Others;
2+
3+
4+
/**
5+
* Dijkstra's algorithm,is a graph search algorithm that solves the single-source
6+
* shortest path problem for a graph with nonnegative edge path costs, producing
7+
* a shortest path tree.
8+
*
9+
* NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
10+
* of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
11+
*
12+
* Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
13+
* Also most of the comments are from RosettaCode.
14+
*
15+
*/
16+
//import java.io.*;
17+
import java.util.*;
18+
public class Dijkstra {
19+
private static final Graph.Edge[] GRAPH = {
20+
new Graph.Edge("a", "b", 7), //Distance from node "a" to node "b" is 7. In the current Graph there is no way to move the other way (e,g, from "b" to "a"), a new edge would be needed for that
21+
new Graph.Edge("a", "c", 9),
22+
new Graph.Edge("a", "f", 14),
23+
new Graph.Edge("b", "c", 10),
24+
new Graph.Edge("b", "d", 15),
25+
new Graph.Edge("c", "d", 11),
26+
new Graph.Edge("c", "f", 2),
27+
new Graph.Edge("d", "e", 6),
28+
new Graph.Edge("e", "f", 9),
29+
};
30+
private static final String START = "a";
31+
private static final String END = "e";
32+
33+
/**
34+
* main function
35+
* Will run the code with "GRAPH" that was defined above.
36+
*/
37+
public static void main(String[] args) {
38+
Graph g = new Graph(GRAPH);
39+
g.dijkstra(START);
40+
g.printPath(END);
41+
//g.printAllPaths();
42+
}
43+
}
44+
45+
class Graph {
46+
private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges
47+
48+
/** One edge of the graph (only used by Graph constructor) */
49+
public static class Edge {
50+
public final String v1, v2;
51+
public final int dist;
52+
public Edge(String v1, String v2, int dist) {
53+
this.v1 = v1;
54+
this.v2 = v2;
55+
this.dist = dist;
56+
}
57+
}
58+
59+
/** One vertex of the graph, complete with mappings to neighbouring vertices */
60+
public static class Vertex implements Comparable<Vertex>{
61+
public final String name;
62+
public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
63+
public Vertex previous = null;
64+
public final Map<Vertex, Integer> neighbours = new HashMap<>();
65+
66+
public Vertex(String name)
67+
{
68+
this.name = name;
69+
}
70+
71+
private void printPath()
72+
{
73+
if (this == this.previous)
74+
{
75+
System.out.printf("%s", this.name);
76+
}
77+
else if (this.previous == null)
78+
{
79+
System.out.printf("%s(unreached)", this.name);
80+
}
81+
else
82+
{
83+
this.previous.printPath();
84+
System.out.printf(" -> %s(%d)", this.name, this.dist);
85+
}
86+
}
87+
88+
public int compareTo(Vertex other)
89+
{
90+
if (dist == other.dist)
91+
return name.compareTo(other.name);
92+
93+
return Integer.compare(dist, other.dist);
94+
}
95+
96+
@Override public String toString()
97+
{
98+
return "(" + name + ", " + dist + ")";
99+
}
100+
}
101+
102+
/** Builds a graph from a set of edges */
103+
public Graph(Edge[] edges) {
104+
graph = new HashMap<>(edges.length);
105+
106+
//one pass to find all vertices
107+
for (Edge e : edges) {
108+
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
109+
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
110+
}
111+
112+
//another pass to set neighbouring vertices
113+
for (Edge e : edges) {
114+
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
115+
//graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
116+
}
117+
}
118+
119+
/** Runs dijkstra using a specified source vertex */
120+
public void dijkstra(String startName) {
121+
if (!graph.containsKey(startName)) {
122+
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
123+
return;
124+
}
125+
final Vertex source = graph.get(startName);
126+
NavigableSet<Vertex> q = new TreeSet<>();
127+
128+
// set-up vertices
129+
for (Vertex v : graph.values()) {
130+
v.previous = v == source ? source : null;
131+
v.dist = v == source ? 0 : Integer.MAX_VALUE;
132+
q.add(v);
133+
}
134+
135+
dijkstra(q);
136+
}
137+
138+
/** Implementation of dijkstra's algorithm using a binary heap. */
139+
private void dijkstra(final NavigableSet<Vertex> q) {
140+
Vertex u, v;
141+
while (!q.isEmpty()) {
142+
143+
u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
144+
if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
145+
146+
//look at distances to each neighbour
147+
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
148+
v = a.getKey(); //the neighbour in this iteration
149+
150+
final int alternateDist = u.dist + a.getValue();
151+
if (alternateDist < v.dist) { // shorter path to neighbour found
152+
q.remove(v);
153+
v.dist = alternateDist;
154+
v.previous = u;
155+
q.add(v);
156+
}
157+
}
158+
}
159+
}
160+
161+
/** Prints a path from the source to the specified vertex */
162+
public void printPath(String endName) {
163+
if (!graph.containsKey(endName)) {
164+
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
165+
return;
166+
}
167+
168+
graph.get(endName).printPath();
169+
System.out.println();
170+
}
171+
/** Prints the path from the source to every vertex (output order is not guaranteed) */
172+
public void printAllPaths() {
173+
for (Vertex v : graph.values()) {
174+
v.printPath();
175+
System.out.println();
176+
}
177+
}
178+
}

0 commit comments

Comments
 (0)