原题链接:399. 除法求值
solution:
图的bfs,a / b = c,无向图相当于存储a 到 b 的距离为c,b 到 a的距离为1 / c
class Solution {
public:
unordered_set<string> node;
unordered_map<string,unordered_map<string,double>> w;
double bfs(string a,string b) {
queue<string> que;
que.push(a);
unordered_map<string,double> d;
d[a] = 1.0; //a / a = 1.0
while(!que.empty()) {
auto t = que.front();
que.pop();
for(auto &p : w[t]) {
if(d.count(p.first)) continue; //如果已经遍历过则跳过
else {
d[p.first] = p.second * d[t];
if(p.first == b) return d[p.first];
que.push(p.first);
}
}
}
return -1;
}
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
for(int i = 0;i <equations.size();i++) {
auto a = equations[i][0];
auto b = equations[i][1];
auto c = values[i]; //a / b = c
w[a][b] = c,w[b][a] = 1 / c;
node.insert(a),node.insert(b);
}
vector<double> res; //定义返回值
for (auto e : queries) {
auto a = e[0], b = e[1];
if (!node.count(a) || !node.count(b)) {res.push_back(-1); continue;}
else if (a == b) {res.push_back(1); continue;}
else res.push_back(bfs(a, b));
}
return res;
}
};