Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
Solution
import java.lang.Double;
public class Solution {
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
if(equations == null || values == null || queries == null) return null;
Map<String, Map<String, Double> > map = new HashMap<String, Map<String, Double>>();
for(int i = 0; i < equations.length; i++) {
if(map.get(equations[i][0]) == null) map.put(equations[i][0], new HashMap<String, Double>());
if(map.get(equations[i][1]) == null) map.put(equations[i][1], new HashMap<String, Double>());
map.get(equations[i][0]).put(equations[i][1], values[i]);
map.get(equations[i][1]).put(equations[i][0], 1.0/values[i]);
}
double ans[] = new double[queries.length];
for(int i = 0; i < queries.length; i++) {
if( map.get(queries[i][0]) == null || map.get(queries[i][1]) == null) {
ans[i] = -1;
} else {
if(queries[i][0].equals(queries[i][1])) {
ans[i] = 1.0;
continue;
}
Double a = dfs(new ArrayList<String>(), 1.0, queries[i][0], queries[i][1], map);
ans[i] = a == null ? -1 : a;
}
}
return ans;
}
public Double dfs(List<String> path, double val, String cur, String target, Map<String, Map<String, Double>> map) {
for(String key: map.get(cur).keySet()) {
if(path.contains(key)) continue;
double v = val * map.get(cur).get(key);
if(key.equals(target)) return v;
path.add(cur);
Double aa = dfs(path, v, key, target, map);
path.remove(path.size() - 1);
if(aa != null) return aa;
}
return null;
}
}