Thursday, January 14, 2021

Lintcode 1257. Evaluate Division

Description

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.

  • The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

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:
Graph + DFS

Code (Java):

public class Solution {
    /**
     * @param equations: 
     * @param values: 
     * @param queries: 
     * @return: return a double type array
     */
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        // write your code here
        double[] ans = new double[queries.size()];
        
        if (equations == null || equations.size() == 0 || values == null|| values.length == 0) {
            return ans;
        }
        
        // build the graph
        Map<String, List<Node>> adjList = new HashMap<>();
        for (int i = 0; i < equations.size(); i++) {
            List<String> equation = equations.get(i);
            double value = values[i];
            String n1 = equation.get(0);
            String n2 = equation.get(1);
            
            // n1->n2
            List<Node> neighbors = adjList.getOrDefault(n1, new ArrayList<>());
            neighbors.add(new Node(n2, value));
            adjList.put(n1, neighbors);
            
            // n2->n1
            List<Node> neighbors2 = adjList.getOrDefault(n2, new ArrayList<>());
            neighbors2.add(new Node(n1, 1.0 / value));
            adjList.put(n2, neighbors2);
        }
        
        // dfs to find the answer
        for (int i = 0; i < queries.size(); i++) {
            List<String> query = queries.get(i);
            String n1 = query.get(0);
            String n2 = query.get(1);
            
            if (!adjList.containsKey(n1) || !adjList.containsKey(n2)) {
                ans[i] = -1.0;
            } else if (n1.equals(n2)) {
                ans[i] = 1.0;
            } else {
                Set<String> visited = new HashSet<>();
                RetVal retval = dfs(n1, n2, adjList, 1.0, visited);
                if (retval.found) {
                    ans[i] = retval.val;
                } else {
                    ans[i]= -1.0;
                }
            }
        }
        
        return ans;
    }
    
    private RetVal dfs(String start, String end, Map<String, List<Node>> adjList, double val, Set<String> visited) {
        RetVal retval = new RetVal(false, -1.0);
        visited.add(start);
        
        if (start.equals(end)) {
            return new RetVal(true, val);
        }
        
        List<Node> neighbors = adjList.get(start);
        
        for (Node neighbor: neighbors) {
            if (visited.contains(neighbor.label)) {
                continue;
            }
            
            retval = dfs(neighbor.label, end, adjList, val * neighbor.val, visited);
            
            if (retval.found) {
                return retval;
            }
        }
        
        visited.remove(start);
        return retval;
    }
}

class Node {
    String label;
    double val;
    
    public Node (String label, double val) {
        this.label = label;
        this.val = val;
    }
}

class RetVal {
    boolean found;
    double val;
    
    public RetVal (boolean found, double val) {
        this.found = found;
        this.val = val;
    }
}

No comments:

Post a Comment