給定兩個單詞(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;}
}