-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0797.cpp
More file actions
39 lines (32 loc) · 915 Bytes
/
Copy path0797.cpp
File metadata and controls
39 lines (32 loc) · 915 Bytes
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
37
38
39
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) {
int n = graph.size();
vector<vector<int>> res;
unordered_set<int> visited;
vector<int> path;
stack<int> st;
st.push(0);
while (!st.empty()) {
int root = st.top();
st.pop();
if (root == n - 1) {
path.push_back(root);
res.push_back(path);
path.pop_back();
continue;
}
if (visited.count(root)) {
visited.erase(root);
path.pop_back();
continue;
}
path.push_back(root);
visited.insert(root);
st.push(root);
for (int n : graph[root])
if (!visited.count(n)) st.push(n);
}
return res;
}
};