这道题考察图,dfs;
思路:关键是要用好stl,平时用的下标取double值,但是C++里就要unordered_map来存储,思路还是那样:首先将图初始化,from和to都应该存入mp中(双向的); 然后开始对每一个queries进行dfs;如果有一个query不存在于mp里,就将ret中放入-1.0, 否则说明可以到达,开始dfs:如果from == to 则放入-1.0, continue, 否则进行dfs。 在dfs中,首先看是否可以直达,是的话就返回val × mp【from】【to】,然后对所有的from可达的点进行判断,如果访问过了,就pass,否则就记录访问过该点,然后继续进行下一层的dfs。
C++ 代码:
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
vector<double> ret;
unordered_map<string, unordered_map<string, double>> mp;
for (int i=0; i<equations.size(); i++) {
string from = equations[i].first;
string to = equations[i].second;
mp[from][to] = values[i];
mp[to][from] = 1.0 / values[i];
}
for (int i=0; i<queries.size(); i++) {
string from = queries[i].first;
string to = queries[i].second;
if (mp.count(from) && mp.count(to)) {
if (from == to) {
ret.push_back(1.0);
continue;
} else {
unordered_set<string> visited;
ret.push_back(dfs(from, to, mp, visited, 1.0));
}
} else {
ret.push_back(-1.0);
}
}
return ret;
}
double dfs(string from, string to, unordered_map<string, unordered_map<string, double>> &mp, unordered_set<string> & visited, double val)
{
if (mp[from].count(to)) {
return mp[from][to] * val;
}
for (pair<string, double> p : mp[from]) {
string str = p.first;
if (visited.count(str) == 0) {
visited.insert(str);
double cur = dfs(str, to, mp, visited, val*p.second);
if (cur != -1.0)
return cur;
}
}
return -1.0;
}
};