目录
一、题目内容
二、解题思路
三、代码
给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。
另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。
返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。
注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。
示例 1:
输入:equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释:
条件:a / b = 2.0, b / c = 3.0
问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]
示例 2:
输入:equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
输出:[3.75000,0.40000,5.00000,0.20000]
示例 3:
输入:equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
输出:[0.50000,2.00000,-1.00000,-1.00000]
提示:
1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj 由小写英文字母与数字组成
看着很唬人,实际上建图即可,graph里增加的是每个分式的分子和分母的对应关系,weight里是分式的值,还有对应的倒数, visited存储遍历过的起始节点;
DFS,查找graph里的已有分式条件,以及利用中间节点构建新的分式,无法构建则为0,查询则返回-1.0;
from collections import defaultdict
class Solution:
def calcEquation(self, equations: list, values: list, queries: list) -> list:
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
gragh = defaultdict(set)
weight = defaultdict()
for i in range(len(equations)):
gragh[equations[i][0]].add(equations[i][1])
gragh[equations[i][1]].add(equations[i][0])
weight[(equations[i][0], equations[i][1])] = values[i]
weight[(equations[i][1], equations[i][0])] = float(1 / values[i])
print(gragh)
print(weight)
def dfs(st, ed, visited):
if (st, ed) in weight:
return weight[(st, ed)]
if st not in gragh or ed not in gragh or st in visited:
return 0
visited.add(st)
res = 0
for link in gragh[st]:
res = (dfs(link, ed, visited)) * weight[(st, link)]
if res != 0:
weight[(st, ed)] = res
break
visited.remove(st)
return res
res = []
for q in queries:
ans = dfs(q[0], q[1], set())
if ans == 0:
ans = -1.0
res.append(ans)
return res
if __name__ == '__main__':
equations = [["a", "b"],
["b", "c"]]
values = [2.0, 3.0]
queries = [["a", "c"],
["b", "a"],
["a", "e"],
["a", "a"],
["x", "x"]]
s = Solution()
ans = s.calcEquation(equations, values, queries)
print(ans)