You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.
Return the answers to all queries. If a single answer cannot be determined, return -1.0.
Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.
For each equation Ai / Bi = values[i], we create a directed edge from Ai to Bi with a weight of values[i] and another edge from Bi to Ai with a weight of 1 / values[i].
Handling Queries:
For each query Cj / Dj = ?, we traverse the graph using Depth-First Search (DFS) or Breadth-First Search (BFS) to determine whether there is a path from Cj to Dj.
During the traversal, we multiply the weights along the path to compute the result.
Special Cases:
If either Cj or Dj is not in the graph, or if there is no path between the two nodes, return -1.0.
classSolution:
defcalcEquation(
self,
equations: List[List[str]],
values: List[float],
queries: List[List[str]]
) -> List[float]:
# Build graph graph: Dict[str, Dict[str, float]] = {}
for (a, b), val in zip(equations, values):
if a notin graph:
graph[a] = {}
if b notin graph:
graph[b] = {}
graph[a][b] = val
graph[b][a] =1/ val
# DFS helper function to find the result of a/bdefdfs(node: str, target: str, visited: set, acc: float) -> float:
if node notin graph or target notin graph:
return-1.0if node == target:
return acc
visited.add(node)
for nei, weight in graph[node].items():
if nei notin visited:
res = dfs(nei, target, visited, acc * weight)
if res !=-1.0:
return res
visited.remove(node)
return-1.0# Handle each query ans: List[float] = []
for c, d in queries:
ans.append(dfs(c, d, set(), 1.0))
return ans