Estimated Sanjan:
The idea of Dijkstra's algorithm is to examine all nodes of the graph in an orderly manner. The algorithm stores the priority queue, where the nodes are ordered according to the costs from the very beginning, and at each iteration of the algorithm the following operations are performed:
- Remove from the queue the lowest cost node from the start, N
- Get your neighbors (N ') and their corresponding cost, cost (N) + cost (N, N')
- Insert neighboring nodes N 'into the queue, with priority indicated by their cost
It is true that the algorithm calculates the cost of the path between the start (A in your case) and all the other nodes, but you can stop exploring the algorithm when it reaches the goal (Z in your example). At this point, you know the cost between A and Z and the path connecting them.
I recommend that you use a library that implements this algorithm instead of encoding your own. In Java, you can take a look at the Hipster library , which has a very convenient way to generate graphs and start using search algorithms.
Here you have an example of how to define a schedule and start using Dijstra with Hipster.
// Create a simple weighted directed graph with Hipster where // vertices are Strings and edge values are just doubles HipsterDirectedGraph<String,Double> graph = GraphBuilder.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) .buildDirectedGraph(); // 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"));
You only need to substitute the definition of the graph for your own, and then create an instance of the algorithm, as in the example.
Hope this helps!
Adrián gonzález
source share