LeetCode——399.除法求值

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        
        graph = defaultdict(set)
        weight = defaultdict(float)
        
        #建图
        for i,equ in enumerate(equations):
            graph[equ[0]].add(equ[1])
            graph[equ[1]].add(equ[0])
            weight[tuple(equ)] = values[i]
            weight[(equ[1],equ[0])] = float(1/values[i])
        print(weight)
        print(graph)
        #DFS遍历
        def dfs(start,end,vistied):
            #图中有此边直接返回
            if (start,end) in weight:
                return weight[(start,end)]

            #图中没有这个点直接返回
            if start not in graph or end not in graph:
                return 0

            if start in vistied:
                return 0
            vistied.add(start)
            res = 0

            for tmp in graph[start]:
                res = (dfs(tmp,end,vistied)*weight[(start,tmp)])
                
                if res!=0:
                    weight[(start,end)]=res
                    break
            vistied.remove(start)
            return res
        
        res = []
        for que in queries:
            #用集合记录已经访问的节点
            tmp = dfs(que[0],que[1],set())
            
            if tmp==0:
                tmp = -1.0
            res.append(tmp)
        return res
  • 难点在于如何将这个题目转换成图的思想
  • 建图
    • 将分子作为图的节点
    • 将值作为权重
    • 建立一个有向图
  • 写DFS框架
    • 如果一条边得值存在直接返回该值
    • 如果当前的节点不在图中返回0
    • 设一个哨兵去记录访问过的节点,如果重复出现返回0(剪枝,否则深度太深了)
    • 遍历图的节点,如果遇到res不为0,那就添加新的边进去,然后跳出遍历
  • 遍历
    • 遍历queries
    • 然后计算每个方程的结果,如果是0那就返回-1,否则返回真实值

这个题目的重点在于建图,需要用两个字典去建图,同时字典也是一个比较重要的数据结构,建图部分的代码应该当作一个模板背过。

猜你喜欢

转载自blog.csdn.net/weixin_37724529/article/details/112260902
今日推荐