|
4 | 4 | import collections
|
5 | 5 |
|
6 | 6 |
|
| 7 | +# bfs solution with better precision |
7 | 8 | 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): |
8 | 76 | def frogPosition(self, n, edges, t, target):
|
9 | 77 | """
|
10 | 78 | :type n: int
|
@@ -35,7 +103,8 @@ def dfs(G, target, t, node, parent):
|
35 | 103 |
|
36 | 104 | # Time: O(n)
|
37 | 105 | # Space: O(n)
|
38 |
| -class Solution2(object): |
| 106 | +# dfs solution with recursion |
| 107 | +class Solution4(object): |
39 | 108 | def frogPosition(self, n, edges, t, target):
|
40 | 109 | """
|
41 | 110 | :type n: int
|
|
0 commit comments