Skip to content

Commit f76810b

Browse files
author
Tony
committed
1377.frog-position-after-t-seconds.py
1 parent 1ee5e06 commit f76810b

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

1377.frog-position-after-t-seconds.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from typing import List
2+
3+
#
4+
# @lc app=leetcode id=1377 lang=python3
5+
#
6+
# [1377] Frog Position After T Seconds
7+
#
8+
9+
# @lc code=start
10+
class Solution:
11+
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
12+
transitions = self.build_transition_map(edges)
13+
14+
q = [(1, 1.0)]
15+
while len(q) > 0 and t >= 0:
16+
nq = []
17+
for node, probability in q:
18+
to_nodes = transitions.get(node)
19+
if node == target:
20+
if t == 0 or to_nodes is None:
21+
return probability
22+
else:
23+
return 0.0
24+
if to_nodes is not None:
25+
next_probability = probability / len(to_nodes)
26+
nq.extend((to_node, next_probability) for to_node in transitions[node])
27+
q = nq
28+
t -= 1
29+
return 0.0
30+
31+
def build_transition_map(self, edges):
32+
all_transitions = {}
33+
for from_node, to_node in edges:
34+
if from_node not in all_transitions:
35+
all_transitions[from_node] = []
36+
all_transitions[from_node].append(to_node)
37+
if to_node not in all_transitions:
38+
all_transitions[to_node] = []
39+
all_transitions[to_node].append(from_node)
40+
if len(all_transitions) == 0:
41+
return all_transitions
42+
visited = set()
43+
q = [1]
44+
transitions = {}
45+
while len(q) > 0:
46+
nq = []
47+
for from_node in q:
48+
if from_node not in visited:
49+
visited.add(from_node)
50+
for to_node in all_transitions[from_node]:
51+
if to_node not in visited:
52+
if from_node not in transitions:
53+
transitions[from_node] = []
54+
transitions[from_node].append(to_node)
55+
nq.append(to_node)
56+
q = nq
57+
return transitions
58+
59+
60+
61+
# @lc code=end
62+
63+
from test_utils import run_test
64+
65+
def test(n: int, edges: List[List[int]], t: int, target: int) -> float:
66+
return Solution().frogPosition(n, edges, t, target)
67+
68+
method = test
69+
70+
run_test(method, [1, [], 1, 1], 1.0)
71+
run_test(method, [5, [[1,5],[1,4],[5,3],[3,2]], 3, 2], 0.5)
72+
run_test(method, [3, [[2,1],[3,2]], 1, 2], 1.0)
73+
run_test(method, [7, [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], 2, 4], 0.16666666666666666)
74+
run_test(method, [7, [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], 1, 7], 0.3333333333333333)
75+
run_test(method, [8, [[2,1],[3,2],[4,1],[5,1],[6,4],[7,1],[8,7]], 7, 7], 0.0)

0 commit comments

Comments
 (0)