05. Count the paths

βœ… GFG solution to Count Paths in DAG problem: count total distinct paths from source to destination in a directed acyclic graph using topological sorting and DP. πŸš€

The problem can be found at the following link: πŸ”— Question Link

🧩 Problem Description

Given a Directed Acyclic Graph (DAG) with V nodes labeled from 0 to V-1, and a list of directed edges edges[i] = [u, v] representing a directed edge from node u to node v, find the total number of distinct paths from a given source node S to a destination node D.

πŸ“˜ Examples

Example 1

Input: edges = [[0,1], [0,3], [2,0], [2,1], [1,3]], V = 4, S = 2, D = 3
Output: 3
Explanation: There are 3 ways to reach 3 from 2:
2 -> 1 -> 3,
2 -> 0 -> 3,
2 -> 0 -> 1 -> 3.

Count the paths

Example 2

Input: edges = [[0,1], [1,2], [1,3], [2,3]], V = 4, S = 0, D = 3
Output: 2
Explanation: There are 2 ways to reach 3 from 0:
0 -> 1 -> 2 -> 3,
0 -> 1 -> 3.

Count the paths

πŸ”’ Constraints

  • $2 \le V \le 10^3$

  • $1 \le E = \text{edges.size()} \le \frac{V \times (V - 1)}{2}$

βœ… My Approach

Topological Sort + Dynamic Programming (DP)

Idea:

Since the graph is a DAG (Directed Acyclic Graph), we can perform a topological sort to linearize the nodes in an order that respects dependencies (edges).

  1. Build the adjacency list and an in-degree array (counts of incoming edges per node).

  2. Use Kahn’s algorithm for topological sorting:

    • Initialize a queue with all nodes having zero in-degree.

    • Iteratively remove nodes from the queue, adding them to the topological order, and decrease in-degree of their neighbors.

  3. Initialize a dp array where dp[i] = number of ways to reach the destination D from node i.

    • Set dp[D] = 1 (base case).

  4. Iterate nodes in reverse topological order:

    • For each node u, sum the paths of all its neighbors v: dp[u] += dp[v].

  5. The answer is dp[S] β€” the number of ways from source S to destination D.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(V + E), since each node and edge is processed exactly once during topological sort and DP calculation.

  • Expected Auxiliary Space Complexity: O(V + E), required for adjacency list, in-degree array, DP array, and queue.

πŸ§‘β€πŸ’» Code (C++)

⚑ View Alternative Approaches with Code and Analysis

πŸ“Š 2️⃣ DFS + Memoization

Use a depth‐first search from the source, caching (memoizing) the number of ways from each node to the destination.

Algorithm Steps:

  1. Build an adjacency list graph of size V from edges.

  2. Maintain a memo array of size V, initialized to -1.

  3. Write a recursive function dfs(u) that:

    • If u == dest, return 1.

    • If memo[u] != -1, return memo[u].

    • Otherwise, iterate over all neighbors v of u, sum up dfs(v), store in memo[u], and return it.

  4. Call dfs(src) to get the total number of distinct paths.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(V + E) β€” Each node and edge is processed once thanks to memoization.

  • Auxiliary Space: πŸ’Ύ O(V + E) β€” For adjacency list and memo array, plus recursion stack space.

βœ… Why This Approach?

  • Avoids building an explicit topological order.

  • Caches results of subproblems for efficiency.

⚠️ Caveat:

  • May cause stack overflow on very deep graphs.

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Topo + DP

🟒 O(V + E)

🟒 O(V + E)

Fast, optimal, non-recursive

Slightly more setup (Kahn’s alg)

πŸ”„ DFS + Memoization

🟒 O(V + E)

🟒 O(V + E)

Simple recursive logic

Risk of stack overflow

πŸ† Best Choice by Scenario

🎯 Scenario
πŸ₯‡ Recommended Approach

🌐 Moderate/large DAG, need guaranteed O(V+E)

πŸ₯‡ Topo + DP (Kahn’s)

πŸ“š Simpler code when graph size is small

πŸ₯ˆ DFS + Memoization

πŸ§‘β€πŸ’» Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated