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
相关推荐
Python图像识别21 小时前
75_基于深度学习的咖啡叶片病害检测系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
闲人编程21 小时前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
熬了夜的程序员1 天前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman1 天前
LeetCode Hot100 自用
算法·leetcode·职场和发展
还是码字踏实1 天前
算法题种类与解题思路全面指南:基于LeetCode Hot 100与牛客Top 101
算法·leetcode
雍凉明月夜1 天前
人工智能学习中深度学习之python基础之 类
python·学习
Geo_V1 天前
OpenAI 大模型 API 使用示例
python·chatgpt·openai·大模型应用·llm 开发
Hello_WOAIAI1 天前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
百锦再1 天前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
tokepson1 天前
chatgpt-to-md优化并重新复习
python·ai·技术·pypi·记录