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
相关推荐
Storynone4 分钟前
【Day23】LeetCode:455. 分发饼干,376. 摆动序列,53. 最大子序和
python·算法·leetcode
田里的水稻20 分钟前
ubuntu22.04_构建openclaw开发框架
运维·人工智能·python
萧曵 丶24 分钟前
LangChain Model IO 提示词模版(Python版)
开发语言·python·langchain
zhojiew34 分钟前
为agent实现渐进式Skills能力的思考和实践
linux·python·算法
huan1991101 小时前
Python使用PyMySQL操作MySQL完整指南
数据库·python·mysql
zyq99101_11 小时前
Python日期处理实战代码
python·算法·蓝桥杯
24kHT1 小时前
tensorboard——SummaryWriter
python
高洁012 小时前
数据可视化实战:用AI工具制作专业数据分析图表
人工智能·python·深度学习·信息可视化·transformer
夏星印2 小时前
argparse解析器参数详解
经验分享·笔记·python·学习·argparse
鬓戈3 小时前
SeaweedFS集群上文件遍历和删除
运维·python