给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
输出: 5
解释: 一个最短转换序列是 “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
返回它的长度 5。
代码
class Solution {public int ladderLength(String beginWord, String endWord, List<String> wordList) {Queue<String> queue=new LinkedList<>();boolean[] check=new boolean[wordList.size()];//记录访问了的字符串int len=beginWord.length();for(int i=0;i<wordList.size();i++)//找出与初始字符串只差一位的字符入队{int cnt=0;for(int j=0;j<len;j++){if(wordList.get(i).charAt(j)==beginWord.charAt(j))cnt++;}if(cnt==len-1) {queue.add(wordList.get(i));check[i]=true;}}int res=0;while (!queue.isEmpty())//bfs{int size=queue.size();for(int i=0;i<size;i++){String string=queue.poll();if(string.equals(endWord)) return res+2;//到达了目标字符串for(int j=0;j<wordList.size();j++){if(check[j]) continue;//已经遍历过了int cnt=0;for(int k=0;k<len;k++)//找出与当前字符串只差一位的字符入队{if(wordList.get(j).charAt(k)==string.charAt(k))cnt++;}if(cnt==len-1) {queue.add(wordList.get(j));check[j]=true;}}}res++;}return 0;}
}