給定兩個單詞(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) {Map<String ,Set<String>> set=new HashMap<>();for(int i=0;i<wordList.size();i++)set.put(wordList.get(i),new HashSet<>());for(int i=0;i<wordList.size();i++)//為每個單詞構建可到達的單詞的set{for(int j=i+1;j<wordList.size();j++){if(getDif(wordList.get(i),wordList.get(j))==1){set.get(wordList.get(i)).add(wordList.get(j));set.get(wordList.get(j)).add(wordList.get(i));}}}if(!set.containsKey(endWord)) return 0;Queue<String> queue=new LinkedList<>();Set<String> c=new HashSet<>();for(int i=0;i<wordList.size();i++) if(getDif(wordList.get(i),beginWord)==1)//將開始字符串可到達的字符串入隊{queue.add(wordList.get(i));c.add(wordList.get(i));}if(queue.isEmpty()) return 0;int res=1;while (!queue.isEmpty())//bfs{int size=queue.size();res++;for (int i=0;i<size;i++){String temp=queue.poll();if(temp.equals(endWord)) return res;for(String s:set.get(temp)){if(!c.contains(s)){queue.add(s);c.add(s);}}}}return 0;}public int getDif(String s1, String s2) {///檢查單詞字母相異的個數int ret=0;for(int i=0;i<s1.length();i++){if(s1.charAt(i)!=s2.charAt(i)) ret++;}return ret;}
}