Skip to content

Commit bbe328d

Browse files
authored
Create minimum-genetic-mutation.cpp
1 parent e752745 commit bbe328d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/minimum-genetic-mutation.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n * b), n is the length of gene string, b is size of bank
2+
// Space: O(b)
3+
4+
class Solution {
5+
public:
6+
int minMutation(string start, string end, vector<string>& bank) {
7+
unordered_map<string, bool> lookup;
8+
for (const auto& b : bank) {
9+
lookup.emplace(b, false);
10+
}
11+
12+
queue<pair<string, int>> q;
13+
q.emplace(start, 0);
14+
while (!q.empty()) {
15+
string cur;
16+
int level;
17+
tie(cur, level) = q.front(); q.pop();
18+
19+
if (cur == end) {
20+
return level;
21+
}
22+
23+
for (int i = 0; i < cur.size(); ++i) {
24+
auto cur_copy = cur;
25+
for (const auto& c : {'A', 'T', 'C', 'G'}) {
26+
if (cur_copy[i] == c) {
27+
continue;
28+
}
29+
cur_copy[i] = c;
30+
if (lookup.count(cur_copy) && lookup[cur_copy] == false) {
31+
q.emplace(cur_copy, level + 1);
32+
lookup[cur_copy] = true;
33+
}
34+
}
35+
}
36+
}
37+
38+
return -1;
39+
}
40+
};

0 commit comments

Comments
 (0)