-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
31 lines (31 loc) · 962 Bytes
/
Solution.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
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
unordered_set<string> s;
for (auto& b : bank) s.insert(b);
unordered_map<char, string> mp;
mp['A'] = "TCG";
mp['T'] = "ACG";
mp['C'] = "ATG";
mp['G'] = "ATC";
queue<pair<string, int>> q;
q.push({start, 0});
while (!q.empty()) {
auto p = q.front();
q.pop();
string t = p.first;
int step = p.second;
if (t == end) return step;
for (int i = 0; i < t.size(); ++i) {
for (char c : mp[t[i]]) {
string next = t.substr(0, i) + c + t.substr(i + 1, t.size() - i - 1);
if (s.count(next)) {
q.push({next, step + 1});
s.erase(next);
}
}
}
}
return -1;
}
};