1
+ class GraphNode :
2
+ def __init__ (self , label , neighbors ):
3
+ self .label = label
4
+ self .neighbors = neighbors
5
+
6
+ class Solution (object ):
7
+ def calcEquation (self , equations , values , queries ):
8
+ """
9
+ :type equations: List[List[str]]
10
+ :type values: List[float]
11
+ :type queries: List[List[str]]
12
+ :rtype: List[float]
13
+ """
14
+ hashmap = dict ()
15
+ for i in range (len (equations )):
16
+ start = equations [i ][0 ]
17
+ end = equations [i ][1 ]
18
+ value = values [i ]
19
+ if start not in hashmap :
20
+ startNode = GraphNode (start , [])
21
+ hashmap [start ] = startNode
22
+ else :
23
+ startNode = hashmap [start ]
24
+
25
+ if end not in hashmap :
26
+ endNode = GraphNode (end , [])
27
+ hashmap [end ] = endNode
28
+ else :
29
+ endNode = hashmap [end ]
30
+
31
+ startNode .neighbors .append ((value , endNode ))
32
+ endNode .neighbors .append (((1 / value ), startNode ))
33
+
34
+ res = []
35
+ for q in queries :
36
+ start = q [0 ]
37
+ end = q [1 ]
38
+ # traverse graph
39
+
40
+ if start not in hashmap or end not in hashmap :
41
+ res .append (- 1 )
42
+ continue
43
+ if start == end :
44
+ res .append (1 )
45
+ continue
46
+ queue = []
47
+ visited = set ()
48
+ queue .append ((1 , hashmap [start ]))
49
+ visited .add (hashmap [start ].label )
50
+ find = False
51
+ while queue :
52
+ curr = queue .pop (0 )
53
+ currVal = curr [0 ]
54
+ currNode = curr [1 ]
55
+
56
+ for neighbor in currNode .neighbors :
57
+ neighborVal = neighbor [0 ]
58
+ neighborNode = neighbor [1 ]
59
+ neighborLabel = neighborNode .label
60
+ if neighborLabel in visited :
61
+ continue
62
+ nextVal = currVal * neighborVal
63
+ if neighborLabel == end :
64
+ res .append (nextVal )
65
+ find = True
66
+ break
67
+ visited .add (neighborLabel )
68
+ queue .append ((nextVal , neighborNode ))
69
+ if find :
70
+ break
71
+ if not find :
72
+ res .append (- 1 )
73
+ return res
74
+ sol = Solution ()
75
+ res = sol .calcEquation (equations = [["a" ,"b" ],["b" ,"c" ]], values = [2.0 ,3.0 ], queries = [["a" ,"c" ],["b" ,"a" ],["a" ,"e" ],["a" ,"a" ],["x" ,"x" ]])
76
+ print (res )
0 commit comments