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
相关推荐
jason.zeng@15022075 分钟前
(七)「固化 Rest 接口 + Text-to-SQL 灵活查询」双模式 Agent 架构教程
数据库·python·sql·ai·架构·langchain·ai编程
YEGE学AI算法9 分钟前
KWS语音唤醒系统完整链路:音频前处理、Fbank、阈值与冷却逻辑
python·音视频·语音唤醒·kws·fbank
alphaTao9 分钟前
LeetCode 每日一题 2026/9/28-2026/10/4
算法·leetcode
kida_yuan20 分钟前
不想花钱写了一个 Flask 知识库(续)
python
云樱梦海20 分钟前
5 分钟上手 IndexTTS 2.5 便携包:不用装 Python、不挑显卡、本地离线跑语音克隆
开发语言·python·tts·indextts2.5
Java小白笔记21 分钟前
Java 函数式接口1:从无参任务到自定义多参数查询
java·windows·python
IT_Octopus32 分钟前
【零基础入门 LLM 开发 · Day 10】:LangChain 入门——一条管道符串起 prompt 和模型
python·langchain·prompt
zaemyn20201 小时前
macOS 上 AccessClient 无法唤起?排查 Python 架构与 Windows App 识别问题
windows·python·macos·远程桌面·accessclient
*wait for?1 小时前
利用uv安装python包,并运行jupyter
python·jupyter·uv