原题地址:https://leetcode-cn.com/problems/evaluate-division/
题目描述:
给出方程式 A / B = k, 其中 A 和 B 均为代表字符串的变量, k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 -1.0。
示例 :
给定 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 ]
输入为: vector
基于上述例子,输入如下:
equations(方程式) = [ ["a", "b"], ["b", "c"] ],
values(方程式结果) = [2.0, 3.0],
queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
输入总是有效的。你可以假设除法运算中不会出现除数为0的情况,且不存在任何矛盾的结果。
解题方案:
解题的思路挺好的,对式子构建图结构的数据结构。每次查询时相当于在图中寻找一条路径:
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
from collections import defaultdict
graph = defaultdict(set)
weight = defaultdict()
lookup = {}
for idx,equ in enumerate(equations):
graph[equ[0]].add(equ[1])
graph[equ[1]].add(equ[0])
weight[tuple(equ)] = values[idx]
weight[(equ[1], equ[0])] = float(1 / values[idx])
def dfs(start, end, visited):
if(start, end) in weight:
return weight[(start, end)]
if start not in graph or end not in graph:
return 0
if start in visited:
return 0
visited.add(start)
res = 0
for tmp in graph[start]:
res = (dfs(tmp, end, visited) * weight[(start, tmp)])
if res != 0:
weight[(start,end)] = res
break
visited.remove(start)
return res
res=[]
for que in queries:
tmp = dfs(que[0],que[1],set())
if tmp == 0:
tmp = -1.0
res.append(tmp)
return res
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
dic={}
for (a,b),v in zip(equations,values):
if a not in dic:
dic[a]={b:v}
else:
dic[a][b]=v
if b not in dic:
dic[b]={a:1/v}
else:
dic[b][a]=1/v
def dfs(a,b,f):
if a not in dic or b not in dic:
return -1.0
elif b in dic[a]:
return dic[a][b]
else:
visited=set()
for i in dic[a]:
if i==f:
continue
if i not in visited:
visited.add(i)
v=dfs(i,b,a)
if v!=-1:
return dic[a][i]*v
return -1
return [dfs(a,b,None) for a,b in queries]