-
Notifications
You must be signed in to change notification settings - Fork 0
/
433. Minimum Genetic Mutation.cpp
61 lines (47 loc) · 1.53 KB
/
433. Minimum Genetic Mutation.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// https://leetcode.com/problems/minimum-genetic-mutation/
class Solution
{
public:
int minMutation(string start, string end, vector<string> &bank)
{
int numMutations = 0;
vector<char> dnaCode = {'A', 'C', 'G', 'T'};
queue<string> nodes;
unordered_set<string> genes;
unordered_set<string> visited;
for (string &mutation : bank)
genes.insert(mutation);
if (genes.find(end) == genes.end())
return -1;
nodes.push(start);
visited.insert(start);
while (!nodes.empty())
{
int size = nodes.size();
for (int i = 0; i < size; ++i)
{
string currentGene = nodes.front();
nodes.pop();
if (currentGene == end)
return numMutations;
for (int j = 0; j < currentGene.length(); ++j)
{
string temp = currentGene;
for (int k = 0; k < dnaCode.size(); ++k)
{
temp[j] = dnaCode[k];
if (temp == currentGene || visited.find(temp) != visited.end())
continue;
if (genes.find(temp) != genes.end())
{
nodes.push(temp);
visited.insert(temp);
}
}
}
}
numMutations++;
}
return -1;
}
};