ID | Title | Difficulty | |
---|---|---|---|
Loading... |
797. All Paths From Source to Target
Medium
LeetCode
Backtracking, Depth-First Search, Breadth-First Search, Graph
Problem
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]).
Example 1:
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.
Example 2:
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Example 3:
Input: graph = [[1],[]]
Output: [[0,1]]
Example 4:
Input: graph = [[1,2,3],[2],[3],[]]
Output: [[0,1,2,3],[0,2,3],[0,3]]
Example 5:
Input: graph = [[1,3],[2],[3],[]]
Output: [[0,1,2,3],[0,3]]
Code
class Solution {
List<List<Integer>> res;
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
res = new ArrayList<>();
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < graph.length; i++) {
map.put(i, new ArrayList<>());
for (int nei : graph[i]) {
map.get(i).add(nei);
}
}
List<Integer> path = new ArrayList<>();
path.add(0);
helper(map, 0, graph.length - 1, path);
return res;
}
private void helper(HashMap<Integer, List<Integer>> map, int curr, int target, List<Integer> path) {
if (!map.containsKey(curr)) return;
if (curr == target) {
res.add(new ArrayList<>(path));
return;
}
List<Integer> neis = map.get(curr);
for (int nei : neis) {
path.add(nei);
helper(map, nei, target, path);
path.remove(path.size() - 1);
}
}
}
按 <- 键看上一题!
796. Rotate String
按 -> 键看下一题!
799. Champagne Tower