
Solution Build graph and BFS

- The direction of edge indicates the order of division,
- and the weight of edge indicates the result of division.
class Solution {
class Node {
String var;
double accProduct;
Node(String var, double accProduct) {
this.var = var;
this.accProduct = accProduct;
}
}
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> graph = new HashMap<>();
for (int i = 0; i < equations.size(); i++) {
String dividend = equations.get(i).get(0);
String divisor = equations.get(i).get(1);
double quotient = values[i];
if (!graph.containsKey(dividend)) {
graph.put(dividend, new HashMap<String, Double>());
}
if (!graph.containsKey(divisor)) {
graph.put(divisor, new HashMap<String, Double>());
}
graph.get(dividend).put(divisor, quotient);
graph.get(divisor).put(dividend, 1 / quotient);
}
double[] res = new double[queries.size()];
for(int i = 0; i < queries.size(); i++) {
String start = queries.get(i).get(0);
String end = queries.get(i).get(1);
if (!graph.containsKey(start) || !graph.containsKey(end)) {
res[i] = -1.0;
} else if (start == end) {
res[i] = 1.0;
} else {
res[i] = pathProduct(graph, start, end);
}
}
return res;
}
public double pathProduct(Map<String, Map<String, Double>> graph, String start, String end) {
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(start, 1.0));
Set<String> visited = new HashSet<>();
while(!queue.isEmpty()) {
Node curNode = queue.poll();
if (curNode.var.equals(end)) {
return curNode.accProduct;
}
visited.add(curNode.var);
for (Map.Entry<String, Double> neighbour : graph.get(curNode.var).entrySet()) {
String nextVar = neighbour.getKey();
double pathWeight = neighbour.getValue();
if (visited.contains(nextVar)) {
continue;
}
queue.offer(new Node(nextVar, pathWeight * curNode.accProduct));
}
}
return -1.0;
}
}