思路:BST
方向 :{a,b,c.......z}
设置一个queue ,记录当前位置
先是外层循环(queue != null) 如果 这个循环走完, 说明中间没返回, 直接返回0;
每一次循环 路径++;
然后是 弹出队列中,
然后循环 字符的每一位然后
进行 方向循环,用每一个方向修改字符
如果在wordlist中存在,就放进queue
然后在wordlist删掉当前的
如果直接满足endword
直接返回
class Solution {
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
int n = beginWord.length();
HashSet<String> set = new HashSet<>();
for(String s : wordList)
{
//System.out.println(s);
set.add(s);
}
char[] direction = {'q','w','e','r','t','y','u','i','p',
'o','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'};
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
int ans = 0;
while(!queue.isEmpty())
{
ans ++;
int size = queue.size();
while(size -- > 0)//往外弹
{
StringBuilder str = new StringBuilder(queue.poll());
for(int i = 0; i < n; i ++)
{
//System.out.println(str);
//System.out.println(": "+i);
for(char c : direction)
{
StringBuilder A = new StringBuilder(str);
A.setCharAt(i, c);
String item= new String(A);
//System.out.println(item + " 1111");
if(set.contains(item))
{
//System.out.println(item + "2222");
queue.add(item);
set.remove(item);
if(endWord.equals(item))
return ans + 1;
}
}
}
}
//System.out.println(queue.size() + ": size");
}
return 0;
}
}