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
相关推荐
微学AI2 小时前
内网穿透的应用-服务器日志出现异常怎么办?Python监控、钉钉告警与远程处理教程
服务器·python·钉钉
_Jimmy_11 小时前
Agent 溯源精度提升方案
人工智能·python·langchain
SamChan9012 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步201512 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
颜酱12 小时前
09 | 重构项目结构
人工智能·python·langchain
kisloy13 小时前
【爬虫入门第8讲】Python爬虫反爬入门
开发语言·爬虫·python
Sisphusssss14 小时前
香橙派5plus GPIO
linux·python·ubuntu
颜酱15 小时前
08 | 把维度值同步到 Elasticsearch(生成阶段)
人工智能·python·langchain
hanlin0315 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
久久学姐15 小时前
基础转码学 AI:Java+Python 双语言入门,3 个月可落地实战项目
java·python·ai·转码·实战项目