The only catch is that it only works when we can find a topological ordering.Define a directed acyclic graph (often known as a DAG for short) to be a directed graph, containing no cycle (a cycle is a set of edges forming a loop, and all pointing the same way around the loop).This is known as the single source shortest path problem (s is the source).

(We can view both types of shortest path as being similar if we think of the shortest path from s to s as being one with no edges in it.) Further, the path from s to x must itself be a shortest path (since otherwise concatenating the shortest path with (x,t) would decrease the length of the overall path).For instance, consider the following graph (assume the edges are all directed from left to right): If we start with A, Dijkstra's algorithm will choose the edge (A,x) minimizing d(A, A) length(edge), namely (A, B).It then sets d(A, B)=2 and chooses another edge (y, C) minimizing d(A,y) d(y, C); the only choice is (A, C) and it sets d(A, C)=3.Here's another ordering that always works: define a topological ordering of a directed graph to be one in which, whenever we have an edge from x to y, the ordering visits x before y.If we can define such an ordering, then we can do something like algorithm 2, and be sure that the predecessor of a vertex x is always processed before we process x itself.

## Define single source shortest path algorithm

Theorem: a graph has a topological ordering if and only if it is a directed acyclic graph.One direction of the proof is simple: suppose G is not a DAG, so it has a cycle.In practice it may sometimes faster to build two trees, one from s and one from t, and stop when they run into each other (this usually ends up visiting less of the graph).Just like with Prim's algorithm, we can use heaps to perform the hard part of each iteration (finding the best edge) in logarithmic time.The basic problem: Find the "best" way of getting from s to t where s and t are vertices in a graph.

We measure "best" simply as the sum of edge lengths of a path.

For instance the graph could be a map representing intersections as vertices, road segments as edges; you want to find either the shortest or fastest route from your house to ICS.

Although both of these problems have different solutions, they are both shortest path problems; in one the length of an edge represents the actual mileage of a segment of road, while in the other it represents the time it would take to drive it, but in both cases the important fact is that the total length of a path is measured by adding the lengths of individual edges. there may be a one-way road, or flights in one direction might have different costs than those the other way.

The idea is to go back to algorithms 1 and 2, which required you to visit the vertices in some order.

In those algorithms we defined the order to be sorted by distance from s, which as we have seen works for positive weight edges, but not if there are negative weights.