[LeetCode] Minimum Genetic Mutation

433. Minimum Genetic Mutation

A gene string can be represented by an 8-character long string, with choices from ‘A’, ‘C’, ‘G’, and ‘T’.

Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.

  • For example, “AACCGGTT” —> “AACCGGTA” is one mutation.

There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.

Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.

Note that the starting point is assumed to be valid, so it might not be included in the bank.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
if(start == end) return 0;
int res = 1;
char gene[4] = {'A', 'C', 'G', 'T'};
queue<string> q;
q.push(start);
unordered_set<string> vis;
vis.insert(start);
unordered_set<string> b(bank.begin(), bank.end());
if(!b.count(end)) return -1;
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto g = q.front(); q.pop();
for(int i = 0; i < 8; i++) {
auto cp = g;
for(int j = 0; j < 4; j++) {
cp[i] = gene[j];
if(b.count(cp)) {
if(cp == end) return res;
else if(!vis.count(cp)) {
vis.insert(cp);
q.push(cp);
}
}
}
}
}

res++;
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/LeetCode/minimum-genetic-mutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.