All Paths from Source to Target
ID: 797
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.Idea
Code
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> paths = new ArrayList<>();
List<Integer> currPath = new ArrayList<>();
dfs(graph, 0, graph.length-1, currPath, paths);
return paths;
}
boolean dfs(int[][] graph, int i, int target, List<Integer> currPath, List<List<Integer>> paths){
currPath.add(i);
if(i==target){
return true;
}
for(int j: graph[i]){
if(dfs(graph, j, target, currPath, paths)){
paths.add(new ArrayList<>(currPath));
};
currPath.remove(currPath.size()-1);
}
return false;
}Last updated
