> For the complete documentation index, see [llms.txt](https://wentao-shao.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wentao-shao.gitbook.io/leetcode/graph-search/399.evaluate-division.md).

# 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**.

```java
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;
  }

}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/graph-search/399.evaluate-division.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
