Given a directed acyclic graph (DAG) with n vertices and m edges, find the number of different paths from a given source vertex to a destination vertex.
In a DAG, the number of paths from a node to the destination is the sum of the number of paths from each of its neighbors to the destination. By processing nodes in reverse topological order, we can compute the number of paths efficiently using dynamic programming.
classSolution {
public:int countPaths(int n, vector<vector<int>>& edges, int source, int dest) {
vector<vector<int>> adj(n);
vector<int> indeg(n, 0);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
indeg[e[1]]++;
}
// Topological sort
queue<int> q;
for (int i =0; i < n; ++i) if (indeg[i] ==0) q.push(i);
vector<int> topo;
while (!q.empty()) {
int u = q.front(); q.pop();
topo.push_back(u);
for (int v : adj[u]) if (--indeg[v] ==0) q.push(v);
}
vector<int> dp(n, 0);
dp[dest] =1;
for (int i = n-1; i >=0; --i) {
int u = topo[i];
for (int v : adj[u]) dp[u] += dp[v];
}
return dp[source];
}
};
classSolution {
publicintcountPaths(int n, int[][] edges, int source, int dest) {
List<List<Integer>> adj =new ArrayList<>();
int[] indeg =newint[n];
for (int i = 0; i < n; ++i) adj.add(new ArrayList<>());
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
indeg[e[1]]++;
}
Queue<Integer> q =new LinkedList<>();
for (int i = 0; i < n; ++i) if (indeg[i]== 0) q.add(i);
List<Integer> topo =new ArrayList<>();
while (!q.isEmpty()) {
int u = q.poll();
topo.add(u);
for (int v : adj.get(u)) if (--indeg[v]== 0) q.add(v);
}
int[] dp =newint[n];
dp[dest]= 1;
for (int i = n-1; i >= 0; --i) {
int u = topo.get(i);
for (int v : adj.get(u)) dp[u]+= dp[v];
}
return dp[source];
}
}
classSolution:
defcount_paths(self, n: int, edges: list[list[int]], source: int, dest: int) -> int:
from collections import deque, defaultdict
adj = defaultdict(list)
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] +=1 q = deque([i for i in range(n) if indeg[i] ==0])
topo = []
while q:
u = q.popleft()
topo.append(u)
for v in adj[u]:
indeg[v] -=1if indeg[v] ==0:
q.append(v)
dp = [0] * n
dp[dest] =1for u in reversed(topo):
for v in adj[u]:
dp[u] += dp[v]
return dp[source]