평가 부문 | Leetcode 24일차
You are given equations in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating-point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
예시
Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
직관 - 출발지에서 목적지까지의 경로를 찾고 가장자리 가중치를 곱합니다.
해결책 -
from collections import defaultdict
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
g = defaultdict(list)
for i in range(len(equations)):
eq = equations[i]
val = values[i]
s, d = eq
g[s].append((d, val))
g[d].append((s, 1/val))
head = (equations[0][0], 1)
# print(g)
def dfs(root, path, s, d):
nonlocal st
st.add(root[0])
path = path + [root]
if s in st and d in st:
return path
res = None
for child in g.get(root[0], []):
if child[0] not in st:
res = dfs(child, path, s, d)
if res is not None:
return res
ans = []
for s, d in queries:
if s == d:
if s in g:
ans.append(1)
else:
ans.append(-1)
continue
st = set()
path = dfs((s, 1), [], s, d)
if path is None:
st = set()
path = dfs((d, 1), [], s, d)
if path is None:
ans.append(-1)
else:
flag = False
res = 1
id_p = [el[0] for el in path]
s_i = id_p.index(s)
e_i = id_p.index(d)
if s_i <= e_i:
for i in range(s_i + 1, e_i + 1):
res*= path[i][1]
ans.append(res)
else:
for i in range(s_i, e_i, -1):
res *= 1/path[i][1]
ans.append(res)
return ans
Reference
이 문제에 관하여(평가 부문 | Leetcode 24일차), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/skbhagat40/evaluate-division-leetcode-day-24-6e8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)