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
相关推荐
QC·Rex6 分钟前
AI Agent 任务规划实战:从 ReAct 到 Plan-and-Solve 的完整指南
人工智能·python·react
副露のmagic1 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展
kcuwu.1 小时前
Python面向对象:封装、继承、多态
开发语言·python
YuanDaima20481 小时前
LangChain基础配置与对话模型实战
人工智能·python·langchain·大模型·智能体·langgraph
河西石头1 小时前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置
不懒不懒1 小时前
【卷积神经网络作业实现人脸的关键点定位功能】
开发语言·python
Bert.Cai1 小时前
Python集合简介
开发语言·python
tryCbest1 小时前
Java和Python开发项目部署简介
java·开发语言·python
ZTLJQ1 小时前
任务调度的艺术:Python分布式任务系统完全解析
开发语言·分布式·python
Frostnova丶1 小时前
LeetCode 3474. 字典序最小的生成字符串
算法·leetcode·职场和发展