399.Evaluate-Division

399. Evaluate Division

题目地址

https://leetcode.com/problems/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"] ]. 

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

代码

Approach #1 DFS

Binary relationship is represented as a graph usually. Does the direction of an edge matters? -- Yes. Take a / b = 2 for example, it indicates a --2--> b as well as b --1/2--> a. Thus, it is a directed weighted graph.

class Solution {
  public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String, Map<String, Double>> graph = buildGraph(equations, values);
    double[] result = new double[queries.length];

    for (int i = 0; i < queries.length; i++) {
      result[i] = getPathWeight(queries[i][0], queries[i][1], new HashSet<>(), graph);
    }

    return result;
  }

  private double getPathWeight(String start, String end, Set<String> visited, Map<String, Map<String, Double>> graph) {
    if (!graph.containsKey(start))        return -1.0;

    if (graph.get(start).containsKey(end)) 
      return graph.get(start).get(end);

    visited.add(start);
    for (Map.Entry<String, Double> neighbor: graph.get(start).entrySet()) {
      if (!visited.contains(neighbour.getKey())) {
        double productWeight = getPathWeight(neighbour.getKey(), end, visited, graph);
        if (productWeight != -1.0) {
          return neighbour.getValue() * productWeight;
        }
      }
    }

    return -1.0;
  }

  private Map<String, Map<String, Double>> buildGraph(String[][] equations, double[] values) {
    Map<String, Map<String, Double>> graph = new HashMap<>();
    String u, v;

    for (int i = 0; i < equations.length; i++) {
      u = equations[i][0];
      v = equations[i][1];
      graph.putIfAbsent(u, new HashMap<>());
      graph.get(u).put(v, values[i]);
      graph.putIfAbsent(v, new HashMap<>());
      graph.get(v).put(u, 1 / values[i]);
    }

    return graph;
  }

}

Last updated