|
1 | 1 | # 399. Evaluate Division |
2 | 2 |
|
3 | | -## DFS Recursive Solution |
| 3 | +## DFS Solution |
4 | 4 | - Runtime: O(N) |
5 | 5 | - Space: O(N) |
6 | 6 | - N = Number of unique nodes |
@@ -42,3 +42,46 @@ class Solution: |
42 | 42 | results.append(dfs(graph, start, end, set())) |
43 | 43 | return results |
44 | 44 | ``` |
| 45 | + |
| 46 | +## BFS Solution |
| 47 | +- Runtime: O(N) |
| 48 | +- Space: O(N) |
| 49 | +- N = Number of unique nodes |
| 50 | + |
| 51 | +``` |
| 52 | +from collections import deque |
| 53 | +from collections import defaultdict |
| 54 | +
|
| 55 | +class Solution: |
| 56 | + def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: |
| 57 | + def create_graph(): |
| 58 | + graph = defaultdict(dict) |
| 59 | + for eq, val in zip(equations, values): |
| 60 | + start, end = eq |
| 61 | + graph[start][end] = val |
| 62 | + graph[end][start] = 1.0 / val |
| 63 | + return graph |
| 64 | + |
| 65 | + def bfs(start, end, results): |
| 66 | + queue = deque([(start, 1.0)]) |
| 67 | + visited = set() |
| 68 | + while len(queue) != 0: |
| 69 | + node, curr_prod = queue.pop() |
| 70 | + if node not in graph: |
| 71 | + continue |
| 72 | + if node == end: |
| 73 | + results.append(curr_prod) |
| 74 | + break |
| 75 | + visited.add(node) |
| 76 | + for neighbor, val in graph[node].items(): |
| 77 | + if neighbor not in visited: |
| 78 | + queue.appendleft((neighbor, curr_prod * val)) |
| 79 | + else: |
| 80 | + results.append(-1.0) |
| 81 | +
|
| 82 | + graph = create_graph() |
| 83 | + results = list() |
| 84 | + for start, end in queries: |
| 85 | + bfs(start, end, results) |
| 86 | + return results |
| 87 | +``` |
0 commit comments