Leetcode-Algorithm-Graph-241
-
题目:
-
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.
(通过A/B=K的形式给出一些方程,A和B都是用字符串表示的变量,而K是一个浮点型的实数。给定一些查询的公式,要求根据给定的方程返回对应的答案。如果答案不存在,返回-1.0。)
例子:
给定:a / b = 2.0,b / c = 3.0。
查询:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ? 。
返回:[6.0,0.5,-1.0,1.0,-1.0]。
题解:
方法1:(DFS-深度优先搜索)
通过方程能够计算出来的答案有三种可能:①直接通过原公式得到;②通过公式的自反关系得到;③通过传递关系得到。这三种关系都能通过一个图来表示,顶点表示变量,边表示除法关系。查询想要的结果可以直接通过找到图上两个顶点间的通路得到,所以涉及到图的遍历问题,而且DFS更适合找到两个顶点间的通路。若两个变量的结果需要通过传递关系得到,那么需要把中间结果相乘得到最终结果。
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
unordered_map<string, unordered_map<string, double>> graph;
vector<double> res;
//put all the data in the graph
for (int i = 0; i < values.size(); ++i) {
graph[equations[i].first].insert(make_pair(equations[i].second, values[i]));
if (values[i] != 0)
graph[equations[i].second].insert(make_pair(equations[i].first, 1/values[i]));
}
//begin queries
for (auto query : queries) {
unordered_set<string> visited;
double result = evaluation(query.first, query.second, graph, visited);
if (result != 0)
res.push_back(result);
else
res.push_back(-1.0);
}
return res;
}
double evaluation(string lop, string rop, unordered_map<string, unordered_map<string, double>> graph, unordered_set<string> visited) {
if (graph[lop].find(rop) != graph[lop].end())
return graph[lop][rop];
for (auto nextNode : graph[lop]) {
if (visited.find(nextNode.first) == visited.end()) {
visited.insert(nextNode.first);
double res = evaluation(nextNode.first, rop, graph, visited);
if (res)
return nextNode.second * res;
}
}
return 0;
}
};