1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution: def calcEquation(self, equations, values, queries): graph = collections.defaultdict(dict) n = len(equations) for i in range(n): src, dst = equations[i] graph[src][dst] = values[i] graph[dst][src] = 1.0 / values[i]
ans = [] for start, end in queries: self.res = -1.0 self.dfs(start, end, set(), 1.0, graph) ans.append(self.res) return ans
def dfs(self, start, end, visited, path, graph): if start == end and start in graph: self.res = path return
if start in visited: return
visited.add(start)
for nei in graph[start].keys(): self.dfs(nei, end, visited, path*graph[start][nei], graph)
|