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> equations, vector& values, vector> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector.

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

加权有向图+DFS

Complexity

O(M+N)
O(E)

Code

class Solution {
    Map<String, Map<String, Double>> g = new HashMap<>();
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        for(int i = 0; i < equations.size(); i++){ // construct graph
            List<String> equation = equations.get(i);
            String x = equation.get(0);
            String y = equation.get(1);
            double value = values[i];
            if(!g.containsKey(x)){
                g.put(x, new HashMap<>());
            }
            g.get(x).put(y, value);
            
            if(!g.containsKey(y)){
                g.put(y, new HashMap<>());
            }
            g.get(y).put(x, 1.0/value);
        }
        
        double[] res = new double[queries.size()];
        for(int i = 0; i < queries.size();i++){
            res[i] = divide(queries.get(i).get(0), queries.get(i).get(1), new HashSet<String>());
        } 
        return res;
    }
    
    private double divide(String x, String y, Set<String> visited){
        if(!g.containsKey(x)) return -1;
        if(x.equals(y)) return 1;
        if(g.get(x).containsKey(y)) return g.get(x).get(y);
        
        visited.add(x);
        for(Map.Entry<String, Double> e : g.get(x).entrySet()){
            if(visited.contains(e.getKey()))
                continue;
            double tmp = divide(e.getKey(), y, visited);
            if(tmp == -1) continue;
            return e.getValue() * tmp;
        }
        
        return -1;
    }
}