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
相关推荐
期末考复习中,蓝桥杯都没时间学了几秒前
力扣刷题15
算法·leetcode·职场和发展
工程师老罗4 分钟前
Turtle库的用法
python
Sivan_Xin9 分钟前
拒绝 If-Else 屎山:利用适配器模式(Adapter)构建第三方登录的“防腐层”实战
linux·python·适配器模式
AI Echoes37 分钟前
LangChain Runnable组件重试与回退机制降低程序错误率
人工智能·python·langchain·prompt·agent
im_AMBER44 分钟前
Leetcode 111 两数相加
javascript·笔记·学习·算法·leetcode
TracyCoder1231 小时前
LeetCode Hot100(21/100)——234. 回文链表
算法·leetcode·链表
AAD555888991 小时前
YOLO11-Seg+ContextGuided:智能交通流量估算与拥堵检测实战指南
python
@––––––1 小时前
力扣hot100—系列1
算法·leetcode·职场和发展
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #236:二叉树的最近公共祖先(RMQ转化、Tarjan离线算法等五种实现方案详细解析)
算法·leetcode·二叉树·lca·并查集·最近公共祖先·rmq
rose and war1 小时前
python和jinja版本问题导致的访问报500
python·ios