class Solution {
public int minMutation(String startGene, String endGene, String[] bank) {
if (startGene.equals(endGene)) {
return 0;
}
Set<String> counter = new HashSet<>(Arrays.asList(bank));
if (!counter.contains(endGene)) {
return -1;
}
Set<String> visited = new HashSet<>();
char[] keys = {'A', 'C', 'G', 'T'};
ArrayDeque<String> Q = new ArrayDeque<>();
Q.addLast(startGene);
visited.add(startGene);
int step = 1;
while (!Q.isEmpty()) {
int sz = Q.size();
for (int i = 0; i < sz; i++) {
String cur = Q.removeFirst();
for (int j = 0; j < 8; j++) {
for (int k = 0; k < 4; k++) {
if (keys[k] == cur.charAt(j)) {
continue;
}
StringBuilder sb = new StringBuilder(cur);
sb.setCharAt(j, keys[k]);
String nxt = sb.toString();
if (visited.contains(nxt)) {
continue;
}
if (!counter.contains(nxt)) {
continue;
}
if (nxt.equals(endGene)) {
return step;
}
Q.addLast(nxt);
visited.add(nxt);
}
}
}
step++;
}
return -1;
}
}
433. 最小基因变化
最新推荐文章于 2024-08-25 18:17:58 发布