1118. Ways Through the DAG
A courier company has n depots numbered 0 to n - 1. Every entry [u, v] of edges is a one-way road from depot u to depot v. The road map is guaranteed to contain no cycle, although depot numbers carry no particular order.
A route is a sequence of roads in which each road starts at the depot where the previous one ended. Count the distinct routes that begin at depot source and end at depot target. Two different roads between the same pair of depots give different routes, and when source == target the empty route counts as exactly one route. Return the count modulo 1000000007.
Example 1
- Input:
- n = 5edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[1,2]]source = 0target = 4
- Output:
- 3
- Explanation:
The routes are 0-1-3-4, 0-2-3-4 and 0-1-2-3-4, so there are 3.
Example 2
- Input:
- n = 3edges = [[0,1],[0,1],[1,2],[1,2],[1,2]]source = 0target = 2
- Output:
- 6
- Explanation:
Choose one of 2 roads from depot 0 to 1, then one of 3 roads from 1 to 2: 2 * 3 = 6 routes.
Example 3
- Input:
- n = 4edges = [[0,1],[2,3]]source = 0target = 3
- Output:
- 0
- Explanation:
Depot 3 can only be entered from depot 2, which depot 0 can never reach, so there is no route.
Constraints
1 ≤ n ≤ 100000
0 ≤ edges.length ≤ 300000, each edge is [u, v] with 0 ≤ u, v < n; the graph has no directed cycle and no self-loop
0 ≤ source, target < n
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(n + m)