A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
Note:
Starting point is assumed to be valid, so it might not be included in the bank.
If multiple mutations are needed, all mutations during in the sequence must be valid.
You may assume start and end string is not the same.
Example 1:
start: "AACCGGTT"
end: "AACCGGTA"
bank: ["AACCGGTA"]
return: 1
Example 2:
start: "AACCGGTT"
end: "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
return: 2
Example 3:
start: "AAAAACCC"
end: "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
return: 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-genetic-mutation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的思路:
1、一种新的bfs解题模板题,underorder_set方便查找是否出现过
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
unordered_set<string> valid(bank.begin(), bank.end()); //基因银行
if(valid.count(end) == 0) return -1;
queue<string> q;
int len = start.size(); //基因长度
char gene[4] = {'A', 'C', 'G', 'T'};
q.push(start);
int step = 0;
while(!q.empty()){
step++;
for(int size = q.size(); size > 0; size--){
auto f = q.front();
q.pop();
for(int i = 0; i < len; i++){
char c = f[i];
for(auto j : gene){
f[i] = j;
if(f == end) return step;
if(valid.count(f) == 0) continue;
valid.erase(f);
q.push(f);
}
f[i] = c;
}
}
}
return -1;
}
};