forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-genetic-mutation.cpp
40 lines (35 loc) · 1.11 KB
/
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
// Time: O(n * b), n is the length of gene string, b is size of bank
// Space: O(b)
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
unordered_map<string, bool> lookup;
for (const auto& b : bank) {
lookup.emplace(b, false);
}
queue<pair<string, int>> q;
q.emplace(start, 0);
while (!q.empty()) {
string cur;
int level;
tie(cur, level) = q.front(); q.pop();
if (cur == end) {
return level;
}
for (int i = 0; i < cur.size(); ++i) {
auto cur_copy = cur;
for (const auto& c : {'A', 'T', 'C', 'G'}) {
if (cur_copy[i] == c) {
continue;
}
cur_copy[i] = c;
if (lookup.count(cur_copy) && lookup[cur_copy] == false) {
q.emplace(cur_copy, level + 1);
lookup[cur_copy] = true;
}
}
}
}
return -1;
}
};