Skip to content

Commit a4e9f37

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

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed

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

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,75 @@
44
import collections
55

66

7+
# bfs solution with better precision
78
class Solution(object):
9+
def frogPosition(self, n, edges, t, target):
10+
"""
11+
:type n: int
12+
:type edges: List[List[int]]
13+
:type t: int
14+
:type target: int
15+
:rtype: float
16+
"""
17+
G = collections.defaultdict(list)
18+
for u, v in edges:
19+
G[u].append(v)
20+
G[v].append(u)
21+
22+
stk = [(t, 1, 0, 1)]
23+
while stk:
24+
new_stk = []
25+
while stk:
26+
t, node, parent, choices = stk.pop()
27+
if not t or not (len(G[node])-(parent != 0)):
28+
if node == target:
29+
return 1.0/choices
30+
continue
31+
for child in G[node]:
32+
if child == parent:
33+
continue
34+
new_stk.append((t-1, child, node,
35+
choices*(len(G[node])-(parent != 0))))
36+
stk = new_stk
37+
return 0.0
38+
39+
40+
# Time: O(n)
41+
# Space: O(n)
42+
# dfs solution with stack with better precision
43+
class Solution2(object):
44+
def frogPosition(self, n, edges, t, target):
45+
"""
46+
:type n: int
47+
:type edges: List[List[int]]
48+
:type t: int
49+
:type target: int
50+
:rtype: float
51+
"""
52+
G = collections.defaultdict(list)
53+
for u, v in edges:
54+
G[u].append(v)
55+
G[v].append(u)
56+
57+
stk = [(t, 1, 0, 1)]
58+
while stk:
59+
t, node, parent, choices = stk.pop()
60+
if not t or not (len(G[node])-(parent != 0)):
61+
if node == target:
62+
return 1.0/choices
63+
continue
64+
for child in G[node]:
65+
if child == parent:
66+
continue
67+
stk.append((t-1, child, node,
68+
choices*(len(G[node])-(parent != 0))))
69+
return 0.0
70+
71+
72+
# Time: O(n)
73+
# Space: O(n)
74+
# dfs solution with recursion with better precision
75+
class Solution3(object):
876
def frogPosition(self, n, edges, t, target):
977
"""
1078
:type n: int
@@ -35,7 +103,8 @@ def dfs(G, target, t, node, parent):
35103

36104
# Time: O(n)
37105
# Space: O(n)
38-
class Solution2(object):
106+
# dfs solution with recursion
107+
class Solution4(object):
39108
def frogPosition(self, n, edges, t, target):
40109
"""
41110
:type n: int

0 commit comments

Comments
 (0)