If you only
want the search to stop once the least cost path to the destination
has been found
, Dijkstra's algorithm can already do that efficiently. You can have the algorithm to return once the target node's status is changed from "grey" to "final". Quoting wikipedia
If we are only interested in a shortest path between vertices source
and target, we can terminate the search at line 13 if u = target.
1 function Dijkstra(Graph, source):
2 dist[source] := 0 // Distance from source to source
3 for each vertex v in Graph: // Initializations
4 if v ≠ source
5 dist[v] := infinity // Unknown distance function from source to v
6 previous[v] := undefined // Previous node in optimal path from source
7 end if
8 add v to Q // All nodes initially in Q
9 end for
10
11 while Q is not empty: // The main loop
12 u := vertex in Q with min dist[u] // Source node in first case
13 remove u from Q
14
15 for each neighbor v of u: // where v has not yet been removed from Q.
16 alt := dist[u] + length(u, v)
17 if alt < dist[v]: // A shorter path to v has been found
18 dist[v] := alt
19 previous[v] := u
20 end if
21 end for
22 end while
23 return dist[], previous[]
24 end function
A* solves a different aspect, and is only useful when you have a meaningful heuristic estimate of how close you are to the target node.
Also, if
The cost of going from one station to another is the same at every
link
,i.e. if path length is the number of links from origin to destination, then shortest path reduces to a depth first search. Using a DFS algorithm may be more efficient.
Additional Note:
In Dijkstra's algorithm, when a node is extracted from the top element u
of the priority queue in line 12
, its distance label is fixed, and it's impossible to find a smaller distance label than what u
currently has. That is why u can be removed in line 13
. You can prove this via techniques similar to mathematical induction. If other words, after u
is removed from Q
, it is not possible for Dijkstra to find a shorter path.