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
相关推荐
烤汉堡25 分钟前
Python入门到实战:post请求+cookie+代理
爬虫·python
luod34 分钟前
Python异常链
python
Swift社区1 小时前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode
我不是QI1 小时前
周志华《机器学习---西瓜书》 一
人工智能·python·机器学习·ai
今天没ID1 小时前
Python 编程实战:从基础语法到算法实现 (1)
python
资深web全栈开发2 小时前
LeetCode 1015. 可被 K 整除的最小整数 - 数学推导与鸽巢原理
算法·leetcode·职场和发展
二川bro2 小时前
Python在AI领域应用全景:2025趋势与案例
开发语言·人工智能·python
leoufung2 小时前
链表题目讲解 —— 删除链表的倒数第 n 个节点(LeetCode 19)
数据结构·leetcode·链表
棒棒的皮皮2 小时前
【Python】Open3d用于3D测高项目
python·3d·open3d