399. 除法求值

原题链接: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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值