433. 最小基因变化
双向宽搜记忆化版本
class Solution {
public int minMutation(String start, String end, String[] bank) {
Set<String> dict = new HashSet<>(), st = new HashSet<>(), ed = new HashSet<>(),
menSt = new HashSet<>(), menEd = new HashSet<>();
for (String s : bank) {
dict.add(s);
}
if (!dict.contains(end)) {
return -1;
}
st.add(start);
ed.add(end);
return bfs(st, ed, menSt, menEd, dict, 0);
}
private int bfs(Set<String> st, Set<String> ed, Set<String> menSt, Set<String> menEd, Set<String> dict, int len) {
if (st.size() == 0) {
return -1;
}
if (st.size() > ed.size()) {
return bfs(ed, st, menEd, menSt, dict, len);
}
Set<String> next = new HashSet<>();
char[] mode = {'A', 'C', 'G', 'T'};
for (String s : st) {
StringBuilder temp = new StringBuilder(s);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
temp.setCharAt(i, mode[j]);
String cur = temp.toString();
if (ed.contains(cur)) {
return len + 1;
}
if (menSt.contains(cur)) {
continue;
}
if (dict.contains(cur)) {
next.add(cur);
menSt.add(cur);
}
temp.setCharAt(i, s.charAt(i));
}
}
}
return bfs(next, ed, menSt, menEd, dict, len + 1);
}
}