2
2
// Space: O(n)
3
3
4
4
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 {
5
39
public:
6
40
double frogPosition (int n, vector<vector<int >>& edges, int t, int target) {
7
41
unordered_map<int , vector<int >> G;
@@ -24,7 +58,9 @@ class Solution {
24
58
if (child == parent) {
25
59
continue ;
26
60
}
27
- result += dfs (G, target, t - 1 , child, node);
61
+ if (result = dfs (G, target, t - 1 , child, node)) {
62
+ break ;
63
+ }
28
64
}
29
65
return result / (G.at (node).size () - int (parent != 0 ));
30
66
}
0 commit comments