题目描述:
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
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
unordered_set<string> s;
for(string& gene:bank) s.insert(gene);
if(s.count(end)==0) return -1;
queue<string> q;
q.push(start);
s.erase(start);
unordered_map<string,int> dist;
dist[start]=0;
vector<int> chars={'A','C','G','T'};
while(!q.empty())
{
string cur=q.front();
q.pop();
if(cur==end) return dist[end];
for(int i=0;i<cur.size();i++)
{
for(char c:chars)
{
string next=cur.substr(0,i)+c+cur.substr(i+1);
if(s.count(next))
{
dist[next]=dist[cur]+1;
q.push(next);
s.erase(next);
}
}
}
}
return -1;
}
};
本文探讨了在一个基因库中,从一个起始基因通过最少的单字符变异到达目标基因的问题。利用广度优先搜索算法,文章详细解释了如何在有效基因集中找到最短的变异路径。

被折叠的 条评论
为什么被折叠?



