Skip to content

Commit 726c147

Browse files
committed
Runtime 48 ms (Top 7.91%) | Memory 16.0 MB (Top 10.37%)
1 parent 0c84235 commit 726c147

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,35 @@
1-
class Solution:
1+
class Solution:
22
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
3-
adj = defaultdict(list)
4-
for equation, value in zip(equations, values):
5-
adj[equation[0]].append((equation[1], value))
6-
adj[equation[1]].append((equation[0], 1 / value))
7-
ans = []
8-
for query in queries:
9-
self.bfs(query, adj, ans)
10-
return ans
11-
12-
def bfs(self, query, adj, ans):
13-
x, y = query
14-
queue = deque([(x, 1)])
15-
visited = set([x])
16-
while queue:
17-
for _ in range(len(queue)):
18-
node, r = queue.popleft()
19-
for neighbor, v in adj[node]:
20-
if neighbor == y:
21-
ans.append(r * v)
22-
return
23-
if neighbor not in visited:
24-
queue.append((neighbor, r * v))
25-
visited.add(neighbor)
26-
ans.append(-1.0)
3+
graph = dict()
4+
5+
for (n, d), v in zip(equations, values):
6+
if n not in graph:
7+
graph[n] = []
8+
if d not in graph:
9+
graph[d] = []
10+
11+
graph[n].append((d, v))
12+
graph[d].append((n, 1/v))
13+
14+
def dfs(node, target, product, visited):
15+
if n not in graph or d not in graph:
16+
return -1
17+
18+
if node == target:
19+
return product
20+
21+
visited.add(node)
22+
23+
for neighbor, quotient in graph[node]:
24+
if neighbor not in visited:
25+
soln = dfs(neighbor, target, product * quotient, visited)
26+
if soln != -1:
27+
return soln
28+
29+
return -1
30+
31+
solns = []
32+
for n, d in queries:
33+
solns.append(dfs(n, d, 1, set()))
34+
35+
return solns

0 commit comments

Comments
 (0)