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

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> graph = new HashMap>();
        HashMap> link_value = new HashMap>();
        
        for (int i = 0; i < equations.length; i++) {
            String[] equation = equations[i];
            if (!graph.containsKey(equation[0])) {
                graph.put(equation[0], new ArrayList());
                link_value.put(equation[0], new ArrayList());
            }
            if (!graph.containsKey(equation[1])) {
                graph.put(equation[1], new ArrayList());
                link_value.put(equation[1], new ArrayList());
            }
            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(), 1.0) : -1;
        }
        return result;
    }
    
    private double dfs(HashMap> graph, HashMap> values, String start, String end, HashSet visited, double value) {
        visited.add(start);
        // if (visited.contains(start)) return -1;
        if (start.equals(end)) return value;
        
        
        List next_list = graph.get(start);
        List 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;
    }
}

你可能感兴趣的:(399. Evaluate Division)