-
Notifications
You must be signed in to change notification settings - Fork 9
/
PathsFromSourceToTarget.cpp
36 lines (32 loc) · 1.11 KB
/
PathsFromSourceToTarget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Problem: https://leetcode.com/problems/all-paths-from-source-to-target/
#include <unordered_set>
#include <vector>
using namespace std;
class PathsFromSourceToTarget {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> paths;
unordered_set<int> seen;
vector<int> path;
dfs(graph, seen, paths, path, 0 /* current */, graph.size() - 1 /* target */);
return paths;
}
void dfs(const vector<vector<int>>& graph, unordered_set<int>& seen,
vector<vector<int>>& paths, vector<int>& path, int current, int target) {
if (seen.find(current) != seen.end()) return;
if (current == target) {
path.push_back(current);
paths.push_back(path);
path.pop_back();
return;
}
path.push_back(current);
seen.insert(current);
for (int i = 0; i < graph[current].size(); ++i) {
int next = graph[current][i];
dfs(graph, seen, paths, path, next, target);
}
seen.erase(current);
path.pop_back();
}
};