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
相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python