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
相关推荐
AI蜗牛之家2 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk3 小时前
python打卡第48天
开发语言·python
chengooooooo4 小时前
leetcode Top100 238. 除自身以外数组的乘积|数组系列
算法·leetcode
Eiceblue5 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550405 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂6 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP6 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@6 小时前
Python数据分析7
开发语言·python
老胖闲聊7 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
GalaxyPokemon7 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展