-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluateDivision_399.java
58 lines (53 loc) · 2.07 KB
/
EvaluateDivision_399.java
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
package org.example;
import java.util.*;
public class EvaluateDivision_399 {
static class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
HashMap<String, HashMap<String, Double>> map = new HashMap<>();
for (int i=0;i<equations.size();i++){
String u = equations.get(i).get(0);
String v = equations.get(i).get(1);
double value = values[i];
map.computeIfAbsent(u, k -> new HashMap<>());
map.get(u).put(v,value);
map.computeIfAbsent(v, k -> new HashMap<>());
map.get(v).put(u, 1/value);
}
double[] result = new double[queries.size()];
HashSet visited;
for (int i=0;i<queries.size();i++){
visited = new HashSet();
String start = queries.get(i).get(0);
visited.add(start);
String end = queries.get(i).get(1);
result[i] = dfs(map, start, end, visited);
}
return result;
}
public double dfs(HashMap<String, HashMap<String, Double>> map, String start, String to, HashSet<String> visited){
if (map.get(start)==null){
return -1;
}
double cost = 1;
HashMap<String, Double> children = map.get(start);
if (children.containsKey(to)){
return children.get(to);
}
for (Map.Entry<String, Double> entry : children.entrySet()) {
String v = entry.getKey();
Double value = entry.getValue();
if (!visited.contains(v)) {
visited.add(v);
cost*=value;
double valid = dfs(map, v, to, visited);
if (valid > 0) {
cost *= valid;
return cost;
}
cost/=value;
}
}
return -1;
}
}
}