November 24, 2025
1๋ถํฐ n๊น์ง์ ์ซ์๋ฅผ ์ฌ์ ์ ์์๋ก ์ถ๋ ฅํ๋ ๋ฌธ์ ๋ค. ๋ค๋ง, ํด๋น ์ ๋ ฌ์ O(n) ์๊ฐ ๋ณต์ก๋์ O(1) ๊ณต๊ฐ ๋ณต์ก๋๋ก ํด๊ฒฐํด์ผ ํ๋ค.
์ด ๋ฌธ์ ๋ ๊ทธ๋ํ ๋ฌธ์ ๋ผ๊ณ ์ธ์งํ๋ ๊ฒ์ด ํต์ฌ์ด๋ค. ์ฃผ์ด์ง ๋ฐฉ์ ์๊ณผ ๊ฐ์ ๊ธฐ๋ฐ์ผ๋ก ๊ทธ๋ํ๋ฅผ ์์ฑํ๊ณ , ๊ฐ ์ฟผ๋ฆฌ์ ๋ํด DFS๋ฅผ ์ฌ์ฉํ์ฌ ์์ ๋ณ์์์ ์ข ๋ฃ ๋ณ์๊น์ง์ ๊ฒฝ๋ก๋ฅผ ์ฐพ๊ณ , ๊ฒฝ๋ก์ ์๋ ๊ฐ์ ์ ๊ณฑ์ ๊ณ์ฐํ๋ค.
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
# 1) build graph from equations
graph = defaultdict(list)
for (start, end), val in zip(equations, values):
graph[start].append((end,val))
graph[end].append((start,1/val))
# 2) define DFS to find path product
def dfs(start,end,visited):
if start not in graph or end not in graph:
return -1.0
if start==end:
return 1.0
visited.add(start)
for neighbor,val in graph[start]:
if neighbor in visited:
continue
product = dfs(neighbor, end, visited)
if product != -1.0:
return val*product
return -1.0
# 3) solve each query with DFS
results = []
for start,end in queries:
results.append(dfs(start,end,set()))
return results
Constraints:
1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj consist of lower case English letters and digits.