题目:
题解:
python
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
# 构造图
graph = defaultdict(list)
for (u, v), value in zip(equations, values):
graph[u].append((v, value))
graph[v].append((u, 1 / value))
def dfs(node, target, visited, acc_product):
# 如果找到了目标节点,返回累积乘积
if node == target:
return acc_product
# 标记当前节点为已访问
visited.add(node)
# 遍历当前节点的邻居
for neighbor, value in graph[node]:
if neighbor not in visited:
result = dfs(neighbor, target, visited, acc_product * value)
if result != -1:
return result
return -1
results = []
for start, end in queries:
if start in graph and end in graph:
# 如果起点和终点都在图中,进行DFS
results.append(dfs(start, end, set(), 1.0))
else:
# 否则,结果为-1
results.append(-1.0)
return results