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
相关推荐
测试199816 分钟前
功能测试、自动化测试、性能测试的区别
自动化测试·python·功能测试·测试工具·职场和发展·性能测试·安全性测试
Data_agent1 小时前
1688获得1688店铺所有商品API,python请求示例
java·开发语言·python
一晌小贪欢1 小时前
【Python办公】-图片批量添加文字水印(附代码)
开发语言·python·图片水印·python水印·python添加水印·图片添加水印
海上飞猪1 小时前
【python】基础数据类型
python
万邦科技Lafite1 小时前
一键获取淘宝关键词商品信息指南
开发语言·数据库·python·商品信息·开放api·电商开放平台
Jurio.1 小时前
Python Ray 分布式计算应用
linux·开发语言·python·深度学习·机器学习
爱加糖的橙子2 小时前
Dify升级到Dify v1.10.1-fix修复CVE-2025-55182漏洞
人工智能·python·ai
Pyeako2 小时前
python网络爬虫
开发语言·爬虫·python·requsets库
diegoXie2 小时前
【Python】 中的 * 与 **:Packing 与 Unpacking
开发语言·windows·python