[leetcode]Evaluate Division

除法求值,先建立树,然后使用递归,主要不要进入环。

后来发现x/x = 1.0这条边可以不用,这样只要记录node是不是访问过就可以。

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        
        adjDict = {} # node -> [adjNodes...]
        valueDict = {} # (x, y) -> float
        
        for i in range(len(equations)): # make graph
            x, y = equations[i]
            if x not in adjDict:
                adjDict[x] = set()
            # x / y
            adjDict[x].add(y)
            valueDict[(x, y)] = values[i]
            # y / x
            if y not in adjDict:
                adjDict[y] = set()
            adjDict[y].add(x)
            valueDict[(y, x)] = 1.0 / values[i]
            # itself
            adjDict[x].add(x) 
            valueDict[(x, x)] = 1.0
            adjDict[y].add(y) 
            valueDict[(y, y)] = 1.0
            
        result = []            

        for query in queries:
            visitedQuery = [query]
            tmp = self.calValue(query, adjDict, valueDict, visitedQuery)
            if tmp is not None:
                result.append(tmp)
            else:
                result.append(-1.0)
                
        return result
            
    # None for not exist
    def calValue(self, query, adjDict, valueDict, visitedQuery):
        x, y = query
        if (x, y) in valueDict:
            return valueDict[(x, y)]
        if x not in adjDict:
            return None
        for nextNode in adjDict[x]:
            if (nextNode, y) in visitedQuery:
                continue
            visitedQuery.append((nextNode, y))
            tmp = self.calValue((nextNode, y), adjDict, valueDict, visitedQuery)
            visitedQuery.pop()               
            if tmp is not None:
                return valueDict[(x, nextNode)] * tmp
            
        return None

  

posted @ 2020-02-07 21:09  阿牧遥  阅读(106)  评论(0编辑  收藏  举报