Shortest Paths in DAGs (Topological + Relaxation) — Implementation & Explanation (C++)

Explore this blog post in detail

Blog Images

3 images
Blog Images - Image 1
Swipe
1 / 3

Shortest Paths in DAGs (Topological + Relaxation) — Implementation & Explanation (C++)

Mashrur Rahman
8/12/2025
Graph Algorithms
Published
# Shortest Paths on Directed Acyclic Graphs (DAG) ## Introduction When a directed graph is acyclic (DAG), shortest paths from a given source can be found in **linear time** by performing a topological sort and then relaxing edges in topological order. ## Approach (intuition) - Topologically sort vertices. - Initialize distances with `+∞`, distance[source] = 0. - Scan vertices in topological order; for each outgoing edge `(u→v, w)`, relax: `dist[v] = min(dist[v], dist[u] + w)`. ## Complexity - Time: **O(V + E)** (topological sort + one pass of relaxations) - Space: **O(V + E)** ## Why this is fast Topological order guarantees that when we process `u`, we have already computed the final shortest distance to `u` — no need for repeated relaxations. ## Reference implementation Full file: `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/DAG.cpp` ### Key snippet (topological recursion) ```cpp\nvoid Topological(int s, vector<pair<long long,int>> adj[], vector<int>& vis, stack<int>& res) { vis[s]= 1; for (auto &e: adj[s]) if (!vis[e.first]) Topological(e.first, adj, vis, res); res.push(s); }\n``` ``` ## Example & Usage The repo contains a sample input. The code reconstructs the path and prints both cost and path. ## Practical notes - DAG shortest paths allow negative edge weights (no cycles — so negative cycles impossible). - Validate input is a DAG first (detect cycles) when required. ## Source `https: //github.com/mashrur-rahman-fahim/algorithm/blob/main/DAG.cpp`.

Technologies & Tools

C++Graph AlgorithmsDAGTopological SortVS CodeG++ CompilerGitGitHub

About the Author

External Links

Blog Info

Status:Published
Type:Algorithm Analysis
Category:Graph Algorithms
Author:Mashrur Rahman
Created:8/12/2025

About the Author

M

Mashrur Rahman

Blog Author

Comments (0)

Mashrur Rahman

A passionate full-stack developer dedicated to creating innovative digital solutions that make a difference. Let's build something amazing together.

Get In Touch

Email

mashrur9550@gmail.com

Location

Dhaka, Bangladesh

© 2026 Mashrur Rahman. All rights reserved.