1. Understanding the problem
We are given a Directed Acyclic Graph (DAG) and two nodes:
u → Starting nodev → Destination node
Our task is to count how many different paths exist from u to v.
A path means moving from one node to another by following the directed edges.
We must return the count modulo 1_000_000_007, because the number of paths may be very large.
2. What is a graph?
A graph consists of:
- Vertices (Nodes): Points in the graph.
- Edges: Connections between the nodes.
In a directed graph, an edge has a specific direction. We can travel only in the direction of the arrow.
For example:
0 → 1 → 3
| |
| └──→ 4
|
├──→ 2 → 4
|
└──→ 4
Here, node 0 has three outgoing edges: 1, 2, and 4.
We cannot travel backward unless a reverse edge exists.
3. What is a DAG?
DAG stands for Directed Acyclic Graph.
- Directed: Edges have a direction.
- Acyclic: The graph does not contain any cycle.
A cycle means returning to the same node after travelling through other nodes.
Valid DAG
0 → 1 → 2 → 3
Moves forward without returning to an earlier node.
Cycle
0 → 1 → 2 → 0
Returns to node 0, creating a cycle.
Because a DAG has no cycles, we can safely process nodes in topological order.
4. Given example
adj = [[1, 2, 4], [3, 4], [4], [2], []];
u = 0;
v = 4;
This adjacency list represents:
0 connects to 1, 2, and 4.1 connects to 3 and 4.2 connects to 4.3 connects to 2.4 has no outgoing edges.
Graph diagram:
┌────→ 1 ─────→ 4
│ │
│ └────→ 3 ──→ 2 ──→ 4
│
├──────────→ 2 ──→ 4
│
└────────────────→ 4
We need to count all paths from node 0 to node 4.
The paths are:
0 → 40 → 1 → 40 → 2 → 40 → 1 → 3 → 2 → 4
Total = 4 paths.
5. How do we solve this problem?
We use two techniques:
- Topological Sorting (Kahn's Algorithm) – to arrange nodes in a valid order.
- Dynamic Programming (DP) – to calculate and reuse the number of paths.
Step 1: Topological sorting
Topological sorting arranges nodes so that for every directed edge A → B, node A appears before node B.
We use Kahn's Algorithm:
- Calculate the indegree of every node.
- Put nodes with indegree
0 into a queue. - Remove one node from the queue.
- Add it to the topological list.
- Reduce the indegree of its neighbouring nodes.
- If a neighbour's indegree becomes
0, add it to the queue. - Continue until the queue is empty.
What is indegree?
Indegree means the number of incoming edges to a node.
For our graph:
| Node | Incoming edges | Indegree |
|---|
| 0 | None | 0 |
| 1 | 0 | 1 |
| 2 | 0, 3 | 2 |
| 3 | 1 | 1 |
| 4 | 0, 1, 2 | 3 |
Node 0 has indegree 0, so it is the first node in the queue.
Step 2: Topological order
One valid topological order for this graph is:
0 → 1 → 3 → 2 → 4
This order respects every directed edge.
We will process this order in reverse to calculate the path count from each node to destination 4.
Step 3: Dynamic Programming
We create an array:
int[] dp = new int[n];
dp[node] = number of paths from this node to destination v.
For our example, destination v = 4.
We use this rule:
- If
node == v, then dp[node] = 1. - Otherwise,
dp[node] is the sum of the path counts of all its neighbours.
The recurrence relation:
\[ dp[u] = \sum_{x \in adj[u]} dp[x] \]
Base case:
\[ dp[v] = 1 \]
This means reaching the destination counts as one complete path.
6. Dry run – calculating dp values
We process the topological order in reverse:
Reverse order
4 → 2 → 3 → 1 → 0
Node 4
Node 4 is our destination.
if (node == v)
{
dp[node] = 1;
continue;
}
dp[4] = 1
We have reached our destination. That is one path.
Node 2
Node 2 connects to node 4.
2 → 4
So:
\[ dp[2] = dp[4] = 1 \]
dp[2] = 1
There is one path from node 2 to node 4.
Node 3
Node 3 connects to node 2.
3 → 2 → 4
So:
\[ dp[3] = dp[2] = 1 \]
dp[3] = 1
There is one path from node 3 to node 4.
Node 1
Node 1 connects to nodes 3 and 4.
1 → 3
1 → 4
We calculate:
\[ dp[1] = dp[3] + dp[4] \]
\[ dp[1] = 1 + 1 = 2 \]
dp[1] = 2
Two paths from node 1 to node 4.
Node 0
Node 0 connects to nodes 1, 2, and 4.
0 → 1
0 → 2
0 → 4
We calculate:
\[ dp[0] = dp[1] + dp[2] + dp[4] \]
\[ dp[0] = 2 + 1 + 1 = 4 \]
dp[0] = 4
There are 4 paths from node 0 to node 4.
7. Complete C# solution
using System;
using System.Collections.Generic;
class Solution
{
public int countPaths(List<List<int>> adj, int u, int v)
{
int n = adj.Count;
const int MOD = 1000000007;
int[] indegree = new int[n];
// Step 1: Calculate indegree
for (int i = 0; i < n; i++)
{
foreach (int node in adj[i])
{
indegree[node]++;
}
}
// Step 2: Topological sorting
Queue<int> queue = new Queue<int>();
for (int i = 0; i < n; i++)
{
if (indegree[i] == 0)
queue.Enqueue(i);
}
List<int> topo = new List<int>();
while (queue.Count > 0)
{
int node = queue.Dequeue();
topo.Add(node);
foreach (int next in adj[node])
{
indegree[next]--;
if (indegree[next] == 0)
queue.Enqueue(next);
}
}
// Step 3: DP array
int[] dp = new int[n];
// Step 4: Process in reverse topological order
for (int i = topo.Count - 1; i >= 0; i--)
{
int node = topo[i];
// Destination node
if (node == v)
{
dp[node] = 1;
continue;
}
long count = 0;
// Count paths through neighbours
foreach (int next in adj[node])
{
count = (count + dp[next]) % MOD;
}
dp[node] = (int)count;
}
return dp[u];
}
}
8. Understanding the code line by line
A. Create the indegree array
int[] indegree = new int[n];
This array stores the number of incoming edges for every node.
Initially, all values are 0.
for (int i = 0; i < n; i++)
{
foreach (int node in adj[i])
{
indegree[node]++;
}
}
We traverse every edge in the adjacency list and increase the indegree of the destination node.
For example, if we have:
0 → 1
0 → 2
1 → 2
Then:
B. Create a queue
Queue<int> queue = new Queue<int>();
The queue stores the nodes that are ready to be processed.
for (int i = 0; i < n; i++)
{
if (indegree[i] == 0)
queue.Enqueue(i);
}
We insert nodes that have no incoming edges.
Why indegree 0?
These nodes have no dependencies from other nodes, so they can be processed first.
C. Build the topological order
List<int> topo = new List<int>();
This list stores nodes in topological order.
while (queue.Count > 0)
{
int node = queue.Dequeue();
topo.Add(node);
We remove a node from the queue and add it to our topological list.
foreach (int next in adj[node])
{
indegree[next]--;
if (indegree[next] == 0)
queue.Enqueue(next);
}
}
What happens here?
- We visit all neighbours of the current node.
- We decrease their indegree because the current node has been processed.
- When a neighbour's indegree reaches
0, it is added to the queue.
This builds a valid topological order.
D. Create the DP array
int[] dp = new int[n];
Each dp[node] stores the total number of paths from that node to the destination v.
Initially, all values are 0.
E. Process nodes in reverse order
for (int i = topo.Count - 1; i >= 0; i--)
{
int node = topo[i];
We traverse the topological list backward.
Why reverse order?
Because we need the path counts of the neighbours before calculating the current node's path count.
If 0 → 1, we need to calculate dp[1] before calculating dp[0].
F. Check the destination
if (node == v)
{
dp[node] = 1;
continue;
}
If the current node is the destination:
- We set its path count to
1. continue skips the remaining code in this loop iteration.
We don't count paths that leave the destination and later return to it. The paths we're counting end when they reach v.
G. Calculate the number of paths
long count = 0;
foreach (int next in adj[node])
{
count = (count + dp[next]) % MOD;
}
We visit every neighbour and add the number of paths from that neighbour to our destination.
For example, node 0 has neighbours 1, 2, and 4.
dp[0] = dp[1] + dp[2] + dp[4]
The modulo is applied after every addition to prevent the count from growing too large.
dp[node] = (int)count;
Finally, we save the calculated value in the DP array.
This value can be reused when other nodes need it.
H. Return the answer
return dp[u];
We return the number of paths from the starting node u to the destination v.
In our example:
u = 0
v = 4
dp[0] = 4
So the answer is 4.
9. Why do we use modulo 1,000,000,007?
The number of possible paths in a DAG can become extremely large.
The problem asks us to return the result modulo:
\[ 10^9 + 7 = 1,000,000,007 \]
We use:
const int MOD = 1000000007;
And:
count = (count + dp[next]) % MOD;
This keeps the calculated value within the required range.
10. Time and space complexity
| Complexity | Explanation |
|---|
| Time: O(V + E) | We visit all vertices and edges for topological sorting and DP. |
| Space: O(V) | The indegree array, queue, topological list and DP array use O(V) additional space. |
The adjacency list is already provided, so the auxiliary space complexity is O(V), excluding the input graph.
11. What should you remember from this problem?
Problem-solving pattern
DAG
↓
Topological Sort
↓
Reverse Topological Order
↓
Dynamic Programming
↓
Count Paths
- Graph: Nodes and directed edges.
- DAG: A directed graph without cycles.
- Topological sorting: Orders nodes based on their dependencies.
- DP: Stores already calculated results.
- Reverse topological order: Allows us to calculate a node after its neighbours' results are available.
Whenever a problem asks you to count paths in a DAG, think about Topological Sorting + Dynamic Programming.
This is a useful pattern for many graph problems involving counting paths, dependencies, and reaching a destination.
Join the conversation! Your thoughts help the community grow.