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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| class Solution_DFS{
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { Map<String, Map<String, Double>> g = new HashMap<>(); bulidGraph(g, equations, values); double[] res = new double[queries.size()];
Arrays.fill(res, -1.0);
int index = 0; for(List<String> q: queries){ String a = q.get(0); String b = q.get(1); if(!g.containsKey(a) || !g.containsKey(b)){ index++; }else { dfs(g, a, b, res, index, new HashSet<>(), 1.0); index++; }
} return res;
}
public double[] calcEquation_dfs(List<List<String>> equations, double[] values, List<List<String>> queries) { Map<String, Map<String, Double>> g = new HashMap<>(); bulidGraph(g, equations, values); int index = 0; double[] ans = new double[queries.size()]; for (List<String> q: queries){ String x = q.get(0); String y = q.get(1); if(!g.containsKey(x) || !g.containsKey(y)){ ans[index] = -1.0; index++; continue; } HashSet<String> visited = new HashSet<>(); ans[index] = divide(x, y, g, visited); index++; } return ans; }
private double divide(String a, String b, Map<String, Map<String, Double>> g, Set<String> visitied){ if( a == b){ return 1.0; } visitied.add(a); for(String next: g.get(a).keySet()){ if(visitied.contains(next)) continue; double d = divide(next, b, g, visitied); if(d > 0) return d * g.get(a).get(next); } return -1.0;
}
private void dfs(Map<String, Map<String, Double>> g, String a, String b, double[] res, int index, Set<String> visited, double tmp){ visited.add(a); if(g.get(a) == null || g.get(a).size() == 0){ return; } if(g.get(a).containsKey(b)) { res[index] = g.get(a).get(b) * tmp; return; } for(String next: g.get(a).keySet()){ if(visited.contains(next)) continue; dfs(g, next, b, res, index, visited, g.get(a).get(next) * tmp); }
}
private void bulidGraph(Map<String, Map<String, Double>> g , List<List<String>> equations, double[] values){ int index = 0; for(List<String> e: equations){ String a = e.get(0); String b = e.get(1); g.putIfAbsent(a, new HashMap<>()); g.putIfAbsent(b, new HashMap<>()); g.get(a).put(b, values[index]); g.get(b).put(a, 1.0 / values[index]); index++; g.get(a).put(a, 1.0); g.get(b).put(b, 1.0); }
}
}
|