[LC] 399. Evaluate Division

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"] ]. 

 

class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String, List<GraphNode>> map = new HashMap<>();
        for (int i = 0; i < equations.size(); i++) {
            List<String> curList = equations.get(i);
            if (!map.containsKey(curList.get(0))) {
                map.put(curList.get(0), new ArrayList<>());
            }
            map.get(curList.get(0)).add(new GraphNode(curList.get(1), values[i]));
            if (!map.containsKey(curList.get(1))) {
                map.put(curList.get(1), new ArrayList<>());
            }
            map.get(curList.get(1)).add(new GraphNode(curList.get(0), 1 / values[i]));
        }
        double[] res = new double[queries.size()];
        for (int i = 0; i < queries.size(); i++) {
            List<String> curList = queries.get(i);
            res[i] = find(curList.get(0), curList.get(1), 1, map, new HashSet<>());
        }
        return res;
    }
    
    private double find(String start, String end, double value, Map<String, List<GraphNode>> map, Set<String> visited) {
        if (!map.containsKey(start) || visited.contains(start)) {
            return -1.0;
        }
        if (start.equals(end)) {
            return value;
        }
        visited.add(start);
        for (GraphNode nei: map.get(start)) {
            double result = find(nei.name, end, value * nei.value, map, visited);
            if (result != -1.0) {
                return result;
            }
        }
        visited.remove(start);
        return -1.0;
    }
}

class GraphNode {
    String name;
    double value;
    public GraphNode(String name, double value) {
        this.name = name;
        this.value = value;
    }
}

 

posted @ 2020-06-07 03:50  xuan_abc  阅读(82)  评论(0编辑  收藏  举报