Python | Leetcode Python题解之第399题除法求值

题目:

题解:

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
相关推荐
hakesashou3 分钟前
python怎么写csv文件
开发语言·python
欧阳枫落8 分钟前
pip 换源
开发语言·python·pip
学步_技术1 小时前
Python编码系列—Python组合模式:构建灵活的对象组合
开发语言·python·组合模式
ac-er88881 小时前
在Flask中处理后台任务
后端·python·flask
ac-er88881 小时前
Flask中的钩子函数
后端·python·flask
Book_熬夜!1 小时前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
我的运维人生2 小时前
利用Python与Ansible实现高效网络配置管理
网络·python·ansible·运维开发·技术共享
毕设木哥2 小时前
计算机专业毕业设计推荐-基于python的汽车汽修保养服务平台
大数据·python·计算机·django·汽车·毕业设计·课程设计
程序猿练习生2 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
m0_638971343 小时前
ARM概念
python