433. 最小基因变化

115 阅读1分钟

思路:

广搜即可

class Solution {
public:
unordered_map<string,int> mp;
vector<char> cs={'A','C','G','T'};
struct node{
    string val;
    int count;
};
    int minMutation(string start, string end, vector<string>& bank) {
        for(auto &it:bank) mp[it]++;
        
        queue<node> q;
        q.push({start,0});

        while(q.size()){
            auto t=q.front();
            q.pop();
            
            if(t.val==end) return t.count;
            for(int i=0;i<t.val.length();i++){
                char temp=t.val[i]; // 记录变异前的值
                for(auto c:cs){
                    t.val[i]=c; // 进行变异
                    if(mp[t.val]){  // 看看这个值在不在基因库里
                        mp[t.val]--;    // 记录该值
                        q.push({t.val,t.count+1}); // 入队
                    }
                }
                t.val[i]=tmp; // 回溯
            }
        }
        return -1;
    }
};