Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
The key idea is to use depth-first search (DFS) to explore all possible paths from the source (node 0) to the target (node n-1). At each node, recursively visit all its neighbors, building up the current path. When the target is reached, add the path to the answer.
classSolution {
public List<List<Integer>>allPathsSourceTarget(int[][] graph) {
List<List<Integer>> ans =new ArrayList<>();
List<Integer> path =new ArrayList<>();
dfs(0, graph, path, ans);
return ans;
}
privatevoiddfs(int u, int[][] graph, List<Integer> path, List<List<Integer>> ans) {
path.add(u);
if (u == graph.length- 1) ans.add(new ArrayList<>(path));
elsefor (int v : graph[u]) dfs(v, graph, path, ans);
path.remove(path.size() - 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funallPathsSourceTarget(graph: Array<IntArray>): List<List<Int>> {
val ans = mutableListOf<List<Int>>()
val path = mutableListOf<Int>()
fundfs(u: Int) {
path.add(u)
if (u == graph.size - 1) ans.add(path.toList())
elsefor (v in graph[u]) dfs(v)
path.removeAt(path.size - 1)
}
dfs(0)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defallPathsSourceTarget(self, graph: list[list[int]]) -> list[list[int]]:
ans = []
path = []
defdfs(u: int):
path.append(u)
if u == len(graph) -1:
ans.append(path[:])
else:
for v in graph[u]:
dfs(v)
path.pop()
dfs(0)
return ans