Graph Theory37 sections · 1633 units
Open in Course

Shortest Path Algorithm

Step by step process

Here is the algorithm for shortest path in a DAG:

1.1. Compute topological order

2.2. Initialize dp[source] = 0, all others to \infty

3.3. For each node uu in topological order: For each edge (u,v)(u, v): dp[v] = min(dp[v], dp[u] + w(u,v))

4.4. Output dp[destination]

Here is why this works. When you process node uu, all nodes that can reach uu have already updated it. So dp[u] is finalized and you can safely use it to update neighbors.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.