|
| 1 | +""" |
| 2 | +I learn the solution from @mlaw0. |
| 3 | +He used BFS, so I use DFS. The runtime is almost the same. |
| 4 | +But I think BFS is more suitable in this case, bc we don't have to go down that deep. |
| 5 | +
|
| 6 | +we know if a/b=2, b/c=3, then |
| 7 | +1. b/a=1/2, c/b=1/3 [2] |
| 8 | +2. a/c=2*3, becasue (a/b)*(b/c)=a/c=2*3 |
| 9 | +we can build graph: a->(b, 2), b->(c, 3). |
| 10 | +a->(b, 2) means a-->2-->b |
| 11 | +b->(c, 3) means b-->3-->c |
| 12 | +so if we need a/c, we are finding a-->?-->c, which is a-->2-->b-->3-->c, which is a-->2*3-->c |
| 13 | +
|
| 14 | +first we build the graph [0] |
| 15 | +for every query, we find from the starting point (n1) itself [1] |
| 16 | +in the stack is the next thing we want to check if it is n2 |
| 17 | +we keep on pushing neighbor or neighbor's neighbor to the stack until we find n2 [3] |
| 18 | +
|
| 19 | +to prevent we visit the visited node we use a set to keep track [4] |
| 20 | +
|
| 21 | +we can further optimize the answer by updating the graph at the same time |
| 22 | +bc it is not likely that we build the graph for a single search [5] |
| 23 | +""" |
| 24 | +class Solution(object): |
| 25 | + def calcEquation(self, equations, values, queries): |
| 26 | + def findVal(query): |
| 27 | + n1, n2 = query |
| 28 | + if n1 not in graph or n2 not in graph: return -1.0 |
| 29 | + |
| 30 | + stack = [(n1, 1.0)] #[1] |
| 31 | + visited = set() #[4] |
| 32 | + |
| 33 | + while stack: |
| 34 | + n, val = stack.pop() |
| 35 | + visited.add(n) |
| 36 | + if n==n2: |
| 37 | + return val |
| 38 | + else: |
| 39 | + for nb, nb_val in graph[n]: #nb means neighbor |
| 40 | + if nb not in visited: |
| 41 | + stack.append((nb, nb_val*val)) #[3] |
| 42 | + if n!=n1: graph[n1].append((nb, nb_val*val)) #[5] |
| 43 | + return -1.0 |
| 44 | + |
| 45 | + def addEdge(n1, n2, val): |
| 46 | + if n1 in graph: |
| 47 | + graph[n1].append((n2, val)) |
| 48 | + else: |
| 49 | + graph[n1] = [(n2, val)] |
| 50 | + |
| 51 | + #[0] |
| 52 | + graph = {} |
| 53 | + for (n1, n2), val in zip(equations, values): |
| 54 | + addEdge(n1, n2, val) |
| 55 | + addEdge(n2, n1, 1/val) |
| 56 | + |
| 57 | + return [findVal(query) for query in queries] |
| 58 | + |
0 commit comments