https://leetcode.com/problems/all-paths-from-source-to-target/description/
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
return solve(graph, 0);
}
public List<List<Integer>> solve(int[][] graph, int node) {
int N = graph.length;
List<List<Integer>> ans = new ArrayList();
if (node == N - 1) {
List<Integer> path = new ArrayList();
path.add(N-1);
ans.add(path);
return ans;
}
for (int nei: graph[node]) {
for (List<Integer> path: solve(graph, nei)) {
path.add(0, node);
ans.add(path);
}
}
return ans;
}
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/233331/Java-Beats-100-or-DFS-or-Space-Efficient
It is a directed, acyclic graph of N nodes. So each node will only be visited once in the first approach. So the time complexity is O(|V|+|E|) -> O(n)
http://zxi.mytechroad.com/blog/graph/leetcode-797-all-paths-from-source-to-target/
Given a directed, acyclic graph of
N
nodes. Find all possible paths from node 0
to node N-1
, and return them in any order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
Example: Input: [[1,2], [3], [3], []] Output: [[0,1,3],[0,2,3]] Explanation: The graph looks like this: 0--->1 | | v v 2--->3 There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Note:
- The number of nodes in the graph will be in the range
[2, 15]
. - You can print different paths in any order, but you should keep the order of nodes inside one path.
Since the graph is a directed, acyclic graph, any path from
A
to B
is going to be composed of A
plus a path from any neighbor of A
to B
. We can use a recursion to return the answer.
Algorithm
Let
N
be the number of nodes in the graph. If we are at node N-1
, the answer is just the path {N-1}
. Otherwise, if we are at node node
, the answer is {node} + {path from nei to N-1}
for each neighbor nei
of node
. This is a natural setting to use a recursion to form the answer.- Time Complexity: . We can have exponentially many paths, and for each such path, our prepending operation
path.add(0, node)
will be . - Space Complexity: , the size of the output dominating the final space complexity.
return solve(graph, 0);
}
public List<List<Integer>> solve(int[][] graph, int node) {
int N = graph.length;
List<List<Integer>> ans = new ArrayList();
if (node == N - 1) {
List<Integer> path = new ArrayList();
path.add(N-1);
ans.add(path);
return ans;
}
for (int nei: graph[node]) {
for (List<Integer> path: solve(graph, nei)) {
path.add(0, node);
ans.add(path);
}
}
return ans;
}
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/233331/Java-Beats-100-or-DFS-or-Space-Efficient
List<List<Integer>> paths;
List<Integer> path;
public void dfs(int[][] graph, int curr) {
path.add(curr);
if (curr == (graph.length-1)) {
paths.add(new ArrayList<>(path));
} else {
for(int node:graph[curr])
dfs(graph,node);
}
path.remove(path.size()-1);
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
paths = new ArrayList();
path = new ArrayList();
dfs(graph,0);
return paths;
}
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/118713/Java-DFS-SolutionIt is a directed, acyclic graph of N nodes. So each node will only be visited once in the first approach. So the time complexity is O(|V|+|E|) -> O(n)
One dfs solution is to traverse the graph from start node to the end, and keep track of each node along the path. Each node can be visited many times when it has multiple indegree.
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
path.add(0);
dfsSearch(graph, 0, res, path);
return res;
}
private void dfsSearch(int[][] graph, int node, List<List<Integer>> res, List<Integer> path) {
if (node == graph.length - 1) {
res.add(new ArrayList<Integer>(path));
return;
}
for (int nextNode : graph[node]) {
path.add(nextNode);
dfsSearch(graph, nextNode, res, path);
path.remove(path.size() - 1);
}
}
Another dfs solution is to use memorization. Each node will be only visited once since the sub result from this node has already been recorded. Memorization increses space cost as well as time cost to record existing paths.
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
Map<Integer, List<List<Integer>>> map = new HashMap<>();
return dfsSearch(graph, 0, map);
}
private List<List<Integer>> dfsSearch(int[][] graph, int node, Map<Integer, List<List<Integer>>> map) {
if (map.containsKey(node)) {
return map.get(node);
}
List<List<Integer>> res = new ArrayList<>();
if (node == graph.length - 1) {
List<Integer> path = new LinkedList<>();
path.add(node);
res.add(path);
} else {
for (int nextNode : graph[node]) {
List<List<Integer>> subPaths = dfsSearch(graph, nextNode, map);
for (List<Integer> path : subPaths) {
LinkedList<Integer> newPath = new LinkedList<>(path);
newPath.addFirst(node);
res.add(newPath);
}
}
}
map.put(node, res);
return res;
}
http://zxi.mytechroad.com/blog/graph/leetcode-797-all-paths-from-source-to-target/
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> ans;
vector<int> path{0};
dfs(graph, path, ans);
return ans;
}
private:
void dfs(const vector<vector<int>>& graph,
vector<int>& path, vector<vector<int>>& ans) {
if (path.back() == graph.size() - 1) {
ans.push_back(path);
return;
}
for (int next : graph[path.back()]) {
path.push_back(next);
dfs(graph, path, ans);
path.pop_back();
}
}
// TLE, but after remove useCache, it passed
// need remove duplicate paths
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
if (graph == null)
return new ArrayList<>();
Set<LinkedHashSet<Integer>> allPaths = new HashSet<>();
allPathsSourceTarget(graph, 0, new LinkedHashSet<>(), allPaths);
return allPaths.stream().map(el -> new ArrayList<>(el)).collect(Collectors.toList());
}
private void allPathsSourceTarget(int[][] graph, int node, LinkedHashSet<Integer> path,
Set<LinkedHashSet<Integer>> allPaths) {
path.add(node); // path.add(node) should be here
if (node == graph.length - 1) {
allPaths.add(new LinkedHashSet<>(path)); // mistake: allPaths.add(path);
path.remove(node); // don't miss this
return;
}
// cache
if (useCache(allPaths, node, path)) {
path.remove(node);
return;
}
for (int i = 0; i < graph[node].length; i++) {
allPathsSourceTarget(graph, graph[node][i], path, allPaths);
}
path.remove(node);
}
private boolean useCache(Set<LinkedHashSet<Integer>> allPaths, int node, LinkedHashSet<Integer> path) {
boolean nodeVisited = false;
List<LinkedHashSet<Integer>> newAllPaths = new ArrayList<>();
for (LinkedHashSet<Integer> cache : allPaths) {
if (cache.contains(node)) {
nodeVisited = true;
LinkedHashSet<Integer> newPath = new LinkedHashSet<>(path);
boolean foundIt = false;
for (Integer tmp : cache) {
if (foundIt) {
newPath.add(tmp);
} else if (Objects.equals(tmp, node)) {
foundIt = true;
} // else continue
}
// ConcurrentModificationException
// allPaths.add(newPath);
newAllPaths.add(newPath);// don't miss this
}
}
allPaths.addAll(newAllPaths);
return nodeVisited;
}