-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46. 399. Evaluate Division
58 lines (49 loc) · 1.94 KB
/
46. 399. Evaluate Division
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
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
double [] ans = new double[queries.size()];
Map<String,Map<String,Double>>equationMap = new HashMap<>();
//constructing the equation map
for(int i=0;i<equations.size();i++){
List<String> equation = equations.get(i);
String a = equation.get(0);
String b = equation.get(1);
equationMap.putIfAbsent(a,new HashMap<>());
equationMap.putIfAbsent(b,new HashMap<>());
equationMap.get(a).put(b,values[i]);
equationMap.get(b).put(a,1/values[i]);
}
//solve the query
for(int i=0;i<queries.size();i++){
List<String>query = queries.get(i);
String src= query.get(0);
String target = query.get(1);
//traverse for the solution
ans[i] = dfs(equationMap,src,target,new HashSet<>(),1.0);
}
return ans;
}
private double dfs(Map<String,Map<String,Double>>equationMap,String src,String target,HashSet<String>visited,double weight){
if(!equationMap.containsKey(src)|| !equationMap.containsKey(target)){
return -1;
}
//if src and taget is same - we find our soltuion
if(src.equals(target)){
return weight;
}
visited.add(src);
double res=-1.0;
//connected equation map
Map<String,Double> connected = equationMap.get(src);
for(Map.Entry<String,Double> entry : connected.entrySet()){
String neighbour = entry.getKey();
if(!visited.contains(neighbour)){
res= dfs(equationMap,neighbour,target,visited,weight*entry.getValue());
//if ans found then we will back
if(res!=-1)
break;
}
}
visited.remove(src);
return res;
}
}