-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathall-paths-from-source-lead-to-destination.cpp
43 lines (39 loc) · 1.18 KB
/
all-paths-from-source-lead-to-destination.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
37
38
39
40
41
42
43
// Time: O(n + e)
// Space: O(n + e)
class Solution {
public:
enum Status { UNVISITED, VISITING, DONE };
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
unordered_map<int, vector<int>> children;
for (const auto& edge : edges) {
children[edge[0]].emplace_back(edge[1]);
}
vector<Status> status(n);
return dfs(children, source, destination, &status);
}
private:
bool dfs(const unordered_map<int, vector<int>>& children,
int node,
int destination,
vector<Status> *status) {
if ((*status)[node] == DONE) {
return true;
}
if ((*status)[node] == VISITING) {
return false;
}
(*status)[node] = VISITING;
if (!children.count(node) && node != destination) {
return false;
}
if (children.count(node)) {
for (const auto& child : children.at(node)) {
if (!dfs(children, child, destination, status)) {
return false;
}
}
}
(*status)[node] = DONE;
return true;
}
};