非Y总写法,我用的朴素BFS
代码是可以通过的,不过没懂为啥level需要初始化成0而非1🤔【大佬可以帮我回答一下,笔芯】
此题是127单词接龙的简化版,因为每次只需要替换”A,C,G,T” 即可,而非每次都要遍历26个字母
其他部分基本一致
不用构图,心中有图,peace
class Solution {
public int minMutation(String start, String end, String[] bank) {
if(start.equals(end)) return 1;
int level = 0;
Set<String> bankSet = new HashSet<>();
for(String s : bank){
bankSet.add(s);
}
Set<String> visited = new HashSet<>();
Queue<String> q = new ArrayDeque<>();
q.offer(start);
visited.add(start);
while(!q.isEmpty()){
int size = q.size();
for(int i = 0; i < size; i++){
String cur = q.poll();
if( cur.equals(end)) return level;
List<String> neighbors = getNeighbors(cur.toCharArray(),bankSet);
for(String nei: neighbors){
if(!visited.contains(nei)){
q.offer(nei);
visited.add(nei);
}
}
}
level++;
}
return -1;
}
private List<String> getNeighbors(char[] array, Set<String> bankSet){
List<String> res = new ArrayList<>();
char[] gene = {'A','C','G','T'};
for(int i = 0; i < array.length; i++){
char originalChar = array[i];
for(char ch: gene){
if(ch == originalChar) continue;
array[i] = ch;
String newString = new String(array);
if( bankSet.contains(newString)) res.add(newString);
}
array[i] = originalChar;
}
return res;
}
}