5
5
6
6
7
7
class Solution (object ):
8
+ def frogPosition (self , n , edges , t , target ):
9
+ """
10
+ :type n: int
11
+ :type edges: List[List[int]]
12
+ :type t: int
13
+ :type target: int
14
+ :rtype: float
15
+ """
16
+ def dfs (G , target , t , node , parent ):
17
+ if not t or not (len (G [node ])- (parent != 0 )):
18
+ return int (node == target )
19
+ result = 0
20
+ for child in G [node ]:
21
+ if child == parent :
22
+ continue
23
+ result = dfs (G , target , t - 1 , child , node )
24
+ if result :
25
+ break
26
+ return result * (len (G [node ])- (parent != 0 ))
27
+
28
+ G = collections .defaultdict (list )
29
+ for u , v in edges :
30
+ G [u ].append (v )
31
+ G [v ].append (u )
32
+ choices = dfs (G , target , t , 1 , 0 )
33
+ return 1.0 / choices if choices else 0.0
34
+
35
+
36
+ # Time: O(n)
37
+ # Space: O(n)
38
+ class Solution2 (object ):
8
39
def frogPosition (self , n , edges , t , target ):
9
40
"""
10
41
:type n: int
@@ -16,8 +47,12 @@ def frogPosition(self, n, edges, t, target):
16
47
def dfs (G , target , t , node , parent ):
17
48
if not t or not (len (G [node ])- (parent != 0 )):
18
49
return float (node == target )
19
- result = sum (dfs (G , target , t - 1 , child , node )
20
- for child in G [node ] if child != parent )
50
+ for child in G [node ]:
51
+ if child == parent :
52
+ continue
53
+ result = dfs (G , target , t - 1 , child , node )
54
+ if result :
55
+ break
21
56
return result / (len (G [node ])- (parent != 0 ))
22
57
23
58
G = collections .defaultdict (list )
0 commit comments