Skip to content

Commit c9d571f

Browse files
authored
Update frog-position-after-t-seconds.cpp
1 parent 2cb63db commit c9d571f

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

C++/frog-position-after-t-seconds.cpp

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,40 @@
22
// Space: O(n)
33

44
class Solution {
5+
public:
6+
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
7+
unordered_map<int, vector<int>> G;
8+
G[1] = {};
9+
for (const auto& edge : edges) {
10+
G[edge[0]].emplace_back(edge[1]);
11+
G[edge[1]].emplace_back(edge[0]);
12+
}
13+
int choices = dfs(G, target, t, 1, 0);
14+
return choices ? 1.0 / choices : 0.0;
15+
}
16+
17+
private:
18+
int dfs(const unordered_map<int, vector<int>>& G,
19+
int target, int t, int node, int parent) {
20+
if (!t || !(G.at(node).size() - int(parent != 0))) {
21+
return (node == target);
22+
}
23+
int result = 0;
24+
for (const auto& child : G.at(node)) {
25+
if (child == parent) {
26+
continue;
27+
}
28+
if (result = dfs(G, target, t - 1, child, node)) {
29+
break;
30+
}
31+
}
32+
return result * (G.at(node).size() - int(parent != 0));
33+
}
34+
};
35+
36+
// Time: O(n)
37+
// Space: O(n)
38+
class Solution2 {
539
public:
640
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
741
unordered_map<int, vector<int>> G;
@@ -24,7 +58,9 @@ class Solution {
2458
if (child == parent) {
2559
continue;
2660
}
27-
result += dfs(G, target, t - 1, child, node);
61+
if (result = dfs(G, target, t - 1, child, node)) {
62+
break;
63+
}
2864
}
2965
return result / (G.at(node).size() - int(parent != 0));
3066
}

0 commit comments

Comments
 (0)