You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Dijkstra's algorithm,is a graph search algorithm that solves the single-source
5
+
* shortest path problem for a graph with nonnegative edge path costs, producing
6
+
* a shortest path tree.
7
+
*
8
+
* NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
9
+
* of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
10
+
*
11
+
* Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
12
+
* Also most of the comments are from RosettaCode.
13
+
*
14
+
*/
15
+
16
+
//import java.io.*;
17
+
importjava.util.*;
18
+
publicclassDijkstra {
19
+
privatestaticfinalGraph.Edge[] GRAPH = {
20
+
newGraph.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
+
newGraph.Edge("a", "c", 9),
22
+
newGraph.Edge("a", "f", 14),
23
+
newGraph.Edge("b", "c", 10),
24
+
newGraph.Edge("b", "d", 15),
25
+
newGraph.Edge("c", "d", 11),
26
+
newGraph.Edge("c", "f", 2),
27
+
newGraph.Edge("d", "e", 6),
28
+
newGraph.Edge("e", "f", 9),
29
+
};
30
+
privatestaticfinalStringSTART = "a";
31
+
privatestaticfinalStringEND = "e";
32
+
33
+
/**
34
+
* main function
35
+
* Will run the code with "GRAPH" that was defined above.
36
+
*/
37
+
publicstaticvoidmain(String[] args) {
38
+
Graphg = newGraph(GRAPH);
39
+
g.dijkstra(START);
40
+
g.printPath(END);
41
+
//g.printAllPaths();
42
+
}
43
+
}
44
+
45
+
classGraph {
46
+
privatefinalMap<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
+
publicstaticclassEdge {
50
+
publicfinalStringv1, v2;
51
+
publicfinalintdist;
52
+
publicEdge(Stringv1, Stringv2, intdist) {
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 */
0 commit comments