-
Notifications
You must be signed in to change notification settings - Fork 0
/
1059. All Paths from Source Lead to Destination
64 lines (49 loc) · 1.57 KB
/
1059. All Paths from Source Lead to Destination
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
vector<vector<int>> g;
vector<bool> vis;
bool dfs(int node, int const& dest) {
if(node == dest and g[node].empty())
return true;
if(node != dest and g[node].empty())
return false;
bool ans = true;
vis[node] = true;
for(int &neigh : g[node]) {
if(vis[neigh]) { ans = false; continue; }
ans = ans and dfs(neigh, dest);
}
vis[node] = false;
return ans;
}
public:
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
g.resize(n), vis.resize(n, false);
for(auto &x : edges)
g[x[0]].push_back(x[1]);
return dfs(source, destination);
}
};
class Solution {
vector<vector<int>> g;
vector<bool> vis;
bool dfs(int source, int const& dest) {
if(vis[source] or (source != dest and g[source].empty()))
return false;
if(source == dest and g[source].empty())
return true;
bool ans = true;
vis[source] = true;
for(int &neigh : g[source])
ans = ans and dfs(neigh, dest);
vis[source] = false;
return ans;
}
public:
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
vis.resize(n, false);
g.resize(n);
for(auto &x : edges)
g[x[0]].push_back(x[1]);
return dfs(source, destination);
}
};