Skip to content

Commit 2e087bc

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

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

Python/frog-position-after-t-seconds.py

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,37 @@
55

66

77
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):
839
def frogPosition(self, n, edges, t, target):
940
"""
1041
:type n: int
@@ -16,8 +47,12 @@ def frogPosition(self, n, edges, t, target):
1647
def dfs(G, target, t, node, parent):
1748
if not t or not (len(G[node])-(parent != 0)):
1849
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
2156
return result/(len(G[node])-(parent != 0))
2257

2358
G = collections.defaultdict(list)

0 commit comments

Comments
 (0)