1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { Map<String, Map<String, Double>> graph = buildGraph(equations, values); double[] res = new double[queries.size()]; for (int i = 0; i < res.length; i++){ res[i] = calculate(graph, queries.get(i).get(0), queries.get(i).get(1), new HashSet<String>()); } return res; }
private double calculate(Map<String, Map<String, Double>> graph, String s, String t, HashSet<String> visited){ if (!graph.containsKey(s)) return -1.0; if (graph.get(s).containsKey(t)) return graph.get(s).get(t); visited.add(s); for (Map.Entry<String, Double> neighbor: graph.get(s).entrySet()){ if (!visited.contains(neighbor.getKey())){ double temp = calculate(graph, neighbor.getKey(), t, visited); if (temp != -1) return neighbor.getValue() * temp; } } return -1.0; }
private Map<String, Map<String, Double>> buildGraph(List<List<String>> equations, double[] values){ Map<String, Map<String, Double>> graph = new HashMap<>(); for (int i = 0; i < values.length; i++){ String a = equations.get(i).get(0); String b = equations.get(i).get(1); if (!graph.containsKey(a)) graph.put(a, new HashMap<String, Double>()); graph.get(a).put(b, values[i]); if (!graph.containsKey(b)) graph.put(b, new HashMap<String, Double>()); graph.get(b).put(a, 1 / values[i]); } return graph; } }
|