[LeetCode] All Paths From Source to Target

797. All Paths From Source to Target

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]).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
vector<vector<int>> res;
void backtracking(vector<vector<int>>&g, int c, vector<int>& tmp) {
if(c + 1 == g.size()) {
res.push_back(tmp);
return;
}
for(auto nxt : g[c]) {
tmp.push_back(nxt);
backtracking(g,nxt,tmp);
tmp.pop_back();
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> tmp{0};
backtracking(graph,0,tmp);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/all-paths-from-source-to-target/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.