Algorithm

int[] dagShortestPath(int src, List[] graph) {
  List order = topologicalSort(graph);
  int[] dist = new int[graph.length];
  Arrays.fill(dist, Integer.MAX_VALUE);
  dist[src] = 0;
  for (int u : order)
    if (dist[u] != Integer.MAX_VALUE)
      for (int[] edge : graph[u]) {
        int v = edge[0], w = edge[1];
        if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
      }
  return dist;
}
Advertisement

Why it works

Topological order guarantees when we visit u, all predecessors' distances are final. Relaxing outgoing edges finalizes their tentative distances.

Advertisement

Complexity

O(V+E). Beats Dijkstra's O((V+E) log V) for DAGs.

Longest path

Negate weights → shortest = longest. In DAG only (longest path is NP-hard in general graphs).