经典DFS,芜湖。
class Solution {
private List<List<Integer>> res = new ArrayList<>();
private int n;
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
n = graph.length;
List<Set<Integer>> list = new ArrayList<>();
for (int i = 0; i <= n - 1; i++) {
list.add(new HashSet<>());
for (int num : graph[i]) {
list.get(i).add(num);
}
}
List<Integer> path = new ArrayList<>();
path.add(0);
dfs(list, 0, path, new HashSet<>());
return res;
}
private void dfs(List<Set<Integer>> list, int num, List<Integer> path, Set<Integer> visited) {
if (num == n - 1) {
res.add(new ArrayList(path));
return;
}
Set<Integer> nextNum = list.get(num);
for (int nm : nextNum) {
if (visited.contains(nm)) continue;
visited.add(nm);
path.add(nm);
dfs(list, nm, path, visited);
visited.remove(nm);
path.remove(path.size() - 1);
}
}
}
神笔马良,你值得信赖!