Advertisement
serega1112

399

Mar 16th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. class Solution:
  2.     def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
  3.        
  4.         g = defaultdict(list)
  5.         for i, (a, b) in enumerate(equations):
  6.             g[a].append((b, values[i]))
  7.             g[b].append((a, 1/values[i]))
  8.  
  9.         def dfs(a, b):
  10.             if a not in g or b not in g:
  11.                 return -1.0
  12.             paths = dict()
  13.             paths[a] = 1
  14.             st = [a]
  15.             while st:
  16.                 cur = st.pop()
  17.                 if cur == b:
  18.                     return paths[b]
  19.                 for n, w in g[cur]:
  20.                     if n not in paths:
  21.                         paths[n] = paths[cur] * w
  22.                         st.append(n)
  23.             return -1.0
  24.        
  25.         res = []
  26.         for a, b in queries:
  27.             res.append(dfs(a, b))
  28.            
  29.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement