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"] ].
Solution:DFS 搜索
思路:
建图: Time Complexity: O(V + E) Space Complexity: O(V + E)
for each query:
Time Complexity: O(V + E) Space Complexity: O(V + E)
Solution Code:
class Solution {
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
// build graph
HashMap<String, ArrayList<String>> graph = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<Double>> link_value = new HashMap<String, ArrayList<Double>>();
for (int i = 0; i < equations.length; i++) {
String[] equation = equations[i];
if (!graph.containsKey(equation[0])) {
graph.put(equation[0], new ArrayList<String>());
link_value.put(equation[0], new ArrayList<Double>());
}
if (!graph.containsKey(equation[1])) {
graph.put(equation[1], new ArrayList<String>());
link_value.put(equation[1], new ArrayList<Double>());
}
graph.get(equation[0]).add(equation[1]);
graph.get(equation[1]).add(equation[0]);
link_value.get(equation[0]).add(values[i]);
link_value.get(equation[1]).add(1 / values[i]);
}
// dfs
double[] result = new double[queries.length];
for (int i = 0; i < queries.length; i++) {
String[] query = queries[i];
result[i] = (graph.containsKey(query[0])) ? dfs(graph, link_value, query[0], query[1], new HashSet<String>(), 1.0) : -1;
}
return result;
}
private double dfs(HashMap<String, ArrayList<String>> graph, HashMap<String, ArrayList<Double>> values, String start, String end, HashSet<String> visited, double value) {
visited.add(start);
// if (visited.contains(start)) return -1;
if (start.equals(end)) return value;
List<String> next_list = graph.get(start);
List<Double> value_list = values.get(start);
for (int i = 0; i < next_list.size(); i++) {
if(visited.contains(next_list.get(i))) continue;
double result = dfs(graph, values, next_list.get(i), end, visited, value * value_list.get(i));
if (result != -1) {
return result;
}
}
visited.remove(start);
return -1;
}
}