export default function calcEquation(
equations,
values,
queries,
) {
const graph = new Map();
function addEdge(from, to, weight) {
if (!graph.has(from)) {
graph.set(from, []);
}
graph.get(from)!.push([to, weight]);
}
for (let i = 0; i < equations.length; i++) {
const [a, b] = equations[i];
const value = values[i];
addEdge(a, b, value);
addEdge(b, a, 1 / value);
}
function dfs(
current,
target,
visited,
product
) {
if (current === target) {
return product;
}
visited.add(current);
const neighbors = graph.get(current) ?? [];
for (const [next, weight] of neighbors) {
if (visited.has(next)) {
continue;
}
const result = dfs(next, target, visited, product * weight);
if (result !== -1.0) {
return result;
}
}
return -1.0;
}
const result = [];
for (const [source, target] of queries) {
if (!graph.has(source) || !graph.has(target)) {
result.push(-1.0);
continue;
}
result.push(dfs(source, target, new Set(), 1.0));
}
return result;
}