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
相关推荐
rgb2gray几秒前
AI 的“诚实”指南:一文详解 Conformal Prediction (共形预测) 与 Split Conformal
人工智能·python·机器学习·数据分析·可解释·共性预测·一致性预测
hakesashou3 分钟前
python 如何使数组中的元素不重复
开发语言·python
Filotimo_4 分钟前
JWT的概念
java·开发语言·python
Agilex松灵机器人14 分钟前
持续更新|从零到玩转Moveit机械臂控制(一)
人工智能·python·机器人·学习方法
喵手23 分钟前
《Python爬虫工程化实战》专栏导读|从“脚本能跑”到“系统能交付”:零基础也能做出可部署的 Python 爬虫!
爬虫·python·网络爬虫·爬虫实战·python爬虫·python爬虫工程化·爬虫实战教学
子午30 分钟前
【2026原创】卫星遥感图像识别系统+Python+深度学习+人工智能+算法模型+TensorFlow
人工智能·python·深度学习
王老师青少年编程40 分钟前
GESP(C++)考级(七级&八级)真题及详细题解(汇总版)
c++·题解·真题·gesp·csp·七级·八级
平生不喜凡桃李1 小时前
LeetCode 两数之和/三数之和
算法·leetcode·两数之和·三数之和
hakesashou1 小时前
python怎么将列表排序
python