| 1 | class Solution { |
| 2 | public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { |
| 3 | Map<String, List<Pair<String, Double>>> adj = new HashMap<>(); |
| 4 | for (int i = 0; i < equations.size(); i++) { |
| 5 | List<String> equation = equations.get(i); |
| 6 | adj.computeIfAbsent( |
| 7 | equation.get(0), k -> new ArrayList<>()).add( |
| 8 | new Pair<>(equation.get(1), values[i])); |
| 9 | adj.computeIfAbsent( |
| 10 | equation.get(1), k -> new ArrayList<>()).add( |
| 11 | new Pair<>(equation.get(0), 1 / values[i])); |
| 12 | } |
| 13 | double[] res = new double[queries.size()]; |
| 14 | for (int i = 0; i < queries.size(); i++) { |
| 15 | List<String> query = queries.get(i); |
| 16 | res[i] = bfs(adj, query.get(0), query.get(1)); |
| 17 | } |
| 18 | return res; |
| 19 | } |
| 20 | |
| 21 | private double bfs(Map<String, List<Pair<String, Double>>> adj, String src, String target) { |
| 22 | if (!adj.containsKey(src) || !adj.containsKey(target)) { |