learngraphtheory.org

Guest User

Using app without sign in

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

DAG Shortest Path Calculator

One pass in topological order, negative weights welcome

Shortest paths in a directed acyclic graph: relax the edges in topological order, negative weights allowed

Time: O(V + E)
Space: O(V)
Use Case: Project scheduling, dynamic programming on DAGs, critical paths
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About DAG Shortest Paths

In a directed acyclic graph (DAG), shortest paths from a source can be found in linear time by relaxing the edges in topological order. Unlike Dijkstra's algorithm it allows negative edge weights, and unlike Bellman-Ford it needs only one pass over the edges. The same idea with the weights negated gives longest paths, which is how the critical path of a project schedule is computed.

How it works

First the vertices are put in a topological order, so that every edge points from an earlier vertex to a later one. All distances start at infinity except the source, which gets 0. Then the vertices are taken in that order, and each one relaxes its outgoing edges: if going through it brings a neighbour closer, the neighbour's distance and predecessor are updated. Every path into a vertex comes only from vertices earlier in the order, so the distance of a vertex is final by the time its turn comes. Vertices before the source in the order stay unreachable. The whole method takes O(V + E) time: one topological sort and one relaxation per edge.

Applications

Shortest and longest paths in DAGs schedule projects (the critical path method), order build systems and data pipelines, solve dynamic programming problems whose subproblems form a DAG, such as text segmentation and sequence alignment, and find the cheapest route through layered networks. In algorithms courses it is the standard example of how a topological order turns a problem into a single pass.

Pseudocode

In a directed acyclic graph, shortest paths need neither a priority queue nor repeated passes. Relaxing the edges of each vertex once, in topological order, is enough, and negative weights are allowed.

DagShortestPath(graph, s):
    order = TopologicalSort(graph)
    dist[v] = infinity for every v,  dist[s] = 0
    for each u in order:
        if dist[u] == infinity: continue     // not reachable
        for each edge (u, v) with weight w:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                parent[v] = u
    return dist, parent

The topological order guarantees that every edge into u comes from a vertex earlier in the order. By the time u is processed, all of its predecessors have been finalised and have already relaxed their edges into u, so dist[u] is already the true shortest distance. Each edge is relaxed exactly once, in the one order that makes a single pass sufficient.

Worked example, step by step

Find the shortest paths from S on the example this page loads, the DAG of CLRS figure 24.5, which has two negative edges.

Example graph: Directed edges R-S (5), R-T (3), S-T (2), S-X (6), T-X (7), T-Y (4), T-Z (2), X-Y (-1), X-Z (1) and Y-Z (-2). The topological order is R, S, T, X, Y, Z.

  1. Vertex R. R comes first in the order but is not reachable from S, so its distance stays infinite and its edges are skipped. Relaxing them would add 5 or 3 to infinity, which is meaningless.
  2. Vertex S. dist(S) = 0. Relaxing S-T gives T 2, and S-X gives X 6.
  3. Vertex T. dist(T) = 2 is final. T-X would give 9, which is not better than 6. T-Y gives Y 6, and T-Z gives Z 4.
  4. Vertex X. dist(X) = 6. The negative edge X-Y gives 6 - 1 = 5, which improves Y from 6. X-Z would give 7, worse than 4.
  5. Vertices Y and Z. dist(Y) = 5, and the negative edge Y-Z gives 5 - 2 = 3, improving Z from 4. Z has no outgoing edges, and the pass is complete.

The distances from S are T 2, X 6, Y 5 and Z 3, with R unreachable. The shortest path to Z is S-X-Y-Z with weight 3, even though S-T-Z looks shorter with only two edges and weight 4: the two negative edges make the longer route cheaper. Ten edges were relaxed once each. Dijkstra would have settled Z at 4 too early, and Bellman-Ford would have needed several passes over all ten edges.

Complexity, and where it comes from

Time: O(V + E) · Space: O(V)

The topological sort costs O(V + E) with Kahn's algorithm or DFS. The relaxation pass visits each vertex once and each outgoing edge once, another O(V + E). There is no priority queue, so no log factor, and no repeated passes, so no factor of V. Memory holds the order, the distances and the parent pointers, all O(V). This makes DAG shortest paths the fastest single-source method available, and it applies to every graph without cycles, whatever the signs of the weights.

When to use DAG Shortest Paths, and when not to

If the graph is acyclic, this method beats the general ones. If it is not, it cannot be used at all.

AlternativePrefer it whenCost
Dijkstra's algorithmThe graph may have cycles but all weights are nonnegative.O((V + E) log V)
Bellman-FordThe graph has cycles and negative weights, and you may need to detect negative cycles.O(VE)
Critical path methodYou want the longest path, for example the minimum project duration. Same pass with max instead of min.O(V + E)
BFSAll edges have the same weight, whether or not the graph has cycles.O(V + E)

Common pitfalls

  • Running it on a graph with a cycle. A cycle has no topological order. Kahn's algorithm reveals this by leaving vertices unprocessed, and the algorithm must stop there. Silently using a partial order gives wrong distances.
  • Relaxing edges out of unreachable vertices. Vertices before the source in the order, like R, stay at infinity. In code that uses a large number for infinity, infinity plus a negative weight can look like a real distance. Skip them explicitly.
  • Assuming the source comes first. The source can sit anywhere in the topological order. Start the pass at the beginning of the order anyway, or at the source, but never assume vertices before it are reachable.
  • Forgetting that longest path is easy here. In general graphs the longest simple path is NP-hard, but in a DAG it is the same linear pass with max in place of min. This is exactly how project scheduling computes the critical path.

Frequently asked questions

How do you find shortest paths in a DAG?
Sort the vertices topologically, set the distance of the source to 0 and all others to infinity, then process the vertices in topological order and relax every outgoing edge of each one exactly once.
Can DAG shortest path handle negative weights?
Yes. Because there are no cycles there can be no negative cycles, and the topological order guarantees that every vertex is final before its outgoing edges are relaxed. Negative weights cause no problems at all.
What is the time complexity of shortest paths in a DAG?
O(V + E): one topological sort and one pass over the edges. That is faster than Dijkstra, which needs a priority queue, and much faster than Bellman-Ford, which may need V passes.
How do you find the longest path in a DAG?
Run the same algorithm with every comparison reversed: start the others at minus infinity and keep the larger value when relaxing, or equivalently negate every weight and compute shortest paths. This is the critical path of a project network.
Why can Dijkstra not be used on this graph?
Dijkstra finalises the closest unsettled vertex, assuming no later path can be shorter. With negative edges that assumption fails: here it would settle Z at distance 4 before discovering the cheaper route S-X-Y-Z of weight 3.

Related algorithms: Topological Sort, Bellman-Ford Algorithm, Dijkstra's Algorithm, Critical Path Method (CPM)

Interactive Controls

Zoom Controls

31%
Nodes: 6
Edges: 10