大致思路:广度优先遍历。
可以把end看成树的叶子结点,然后求深度最小的叶子结点的深度。采用层次遍历二叉树,用队列实现,当遇到第一个叶子结点就返回。每遍历一层就为res++。
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
int res = 1;
LinkedList<String> queue = new LinkedList<>();
queue.offer(start);
while(!queue.isEmpty()){
int size = queue.size();
while(size>0){
String s = queue.poll();
size--;
if(isDiffOne(s,end)) return res+1;
for(int i = 0;i<s.length();i++){
char[] charArr = s.toCharArray();
for(char c = 'z';c>='a';c--){
charArr[i] = c;
String n = new String(charArr);
if(dict.contains(n) && isDiffOne(n,s)) {
queue.offer(n);
dict.remove(n);
}
}
}
}
res++;
}
return 0;
}
public boolean isDiffOne(String a, String b){
int c = 0;
for(int i = 0;i<a.length();i++){
if(a.charAt(i)!=b.charAt(i)) c++;
}
return c==1?true:false;
}
}