Recall from the previous section that DAGs are directed, acyclic graphs. If we wanted to find the shortest path on DAGs we could use Dijkstra's. However, with DAGs there's a simple shortest path algorithm which also handles negative edge weights!
Recall that Dijkstra's can fail if negative edges exist because it relies on the assumption that once we visit an edge, we've found the shortest path to that edge. But if negative edge weights can exist ahead of where we can see, then this assumption fails. Consider the following example:
Starting from A, Dijkstra's will visit C first, then B (never even considering the edge
Of course, negative edge weights do not mean Dijkstra's is guaranteed to fail. Dijkstra's succeeds with the following example:
Visit vertices in topological order:
- On each visit, relax all outgoing edges
Recall the definition for relaxing an edge
if distTo[u] + w < distTo[v]:
distTo[v] = distTo[u] + w
edgeTo[v] = u
Since we visit vertices in topological order, a vertex is visited only when all possible info about it has been considered. This means that if negative edge weights exist along a path to
Finding a topological sort takes
What if we want to solve the shortest path problem on graphs that aren't DAGs and also may have negative edges? An extension of Dijkstra's called Bellman Ford can suit your needs, though it is out of scope for this course.