AC代码:
class Solution(object): def calcEquation(self, equations, values, queries): """ :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] """ graph = {} visited = {} # build the graph like [{A:{B:1,C:2}},{B:{A:1}}] for i in range(len(equations)): if equations[i][0] not in graph: graph[equations[i][0]] = {equations[i][1]:values[i]} visited[equations[i][0]] = False else: graph[equations[i][0]][equations[i][1]]=values[i] if values[i] == 0: continue if equations[i][1] not in graph: graph[equations[i][1]] = {equations[i][0]:1/values[i]} visited[equations[i][1]] = False else: graph[equations[i][1]][equations[i][0]]=1/values[i] results = [] res = -1.0 for i in range(len(queries)): if queries[i][0] not in graph: res = -1.0 results.append(res) continue if queries[i][0] == queries[i][1]: res = 1.0 results.append(res) continue if queries[i][1] in graph[queries[i][0]]: res = graph[queries[i][0]][queries[i][1]] results.append(res) continue visited[queries[i][0]] = True for key in graph[queries[i][0]]: visited[key] = True res = self.dfs(graph,key,queries[i][1],graph[queries[i][0]][key],visited) visited[key] = False if res != -1.0: break visited[queries[i][0]] = False results.append(res) return results def dfs(self,graph,start,end,res,visited): if end in graph[start]: res = res*graph[start][end] return res for key in graph[start]: if visited[key] == True: continue visited[key] = True res = self.dfs(graph,key,end,res*graph[start][key],visited) visited[key] = False if res != -1.0: return res return -1.0
解题思路:利用dicts建图,形式为[{A:{B:1,C:2}},{B:{A:1}}],然后使用深度优先搜索,对于不在dicts中的点直接返回-1,如果一次query中两点相等,返回1,否则进行深度优先搜索。参考了http://blog.csdn.net/yeqiuzs/article/details/52506433的方法,建立一个visited词典,保存该点是否访问过,避免形成环。