All Paths From Source to Target LeetCode solution in C++

1
class Solution {
2
public:
3
// setting a few class variables, so that we do not have to pass them down all
4
// the time in the recursive dfs calls
5
int target;
6
vector<vector<int>> res;
7
vector<int> tmp;
8
void dfs(vector<vector<int>> &graph, int currNode = 0) {
9
// updating tmp
10
tmp.push_back(currNode);
11
// and either updating res with it if target is met
12
if (currNode == target) res.push_back(tmp);
13
// or callling dfs again recursively
14
else
15
for (int node : graph[currNode]) {
16
dfs(graph, node);
17
}
18
// backtracking with tmp
19
tmp.pop_back();
20
}
21
vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) {
22
target = graph.size() - 1;
23
dfs(graph);
24
return res;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0