Skip to content

Instantly share code, notes, and snippets.

@pablormier
Last active March 16, 2017 01:35
Show Gist options
  • Save pablormier/3fa802e722d169e63dc6 to your computer and use it in GitHub Desktop.
Save pablormier/3fa802e722d169e63dc6 to your computer and use it in GitHub Desktop.
Directed graph shortest path with Dijkstra and Java
// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph =
GraphBuilder.<String,Double>create()
.connect("A").to("B").withEdge(4d)
.connect("A").to("C").withEdge(2d)
.connect("B").to("C").withEdge(5d)
.connect("B").to("D").withEdge(10d)
.connect("C").to("E").withEdge(3d)
.connect("D").to("F").withEdge(11d)
.connect("E").to("D").withEdge(4d)
.createDirectedGraph();
// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
.startingFrom("A")
.in(graph)
.takeCostsFromEdges()
.build();
// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment