Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed word. For example, Given: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.
假設輸入兩個單詞beginWord,endWord以及一個字典。每一次操做只能對當前單詞修改一個字符成爲字典中的一個單詞。問至少須要多少次操做能夠將beginWord轉化爲endWord。若是不可轉換則返回0。面試
其實若是從遞歸的角度來看,並不是不能夠實現。每一種廣泛狀況也就是將當前單詞修改一個字符成爲當前字典中的一個單詞。可是這種要遍歷全部的狀況,哪怕是已經超過最小操做次數的狀況,致使代碼超時。其實從另外一個角度來講,這道題能夠看作是廣度優先算法的一個展現。算法
按上文中的題目爲例,能夠將廣度優先算法寫成如下形式。微信
hit / hot / \ dot lot / / dog log / / cog cog
也就是說,將每一層上能夠生成的單詞所有列出來,而後再逐層遍歷,一旦出現一個單詞等於endWord,那麼遍歷終止,將當前遍歷的次數返回。這裏要注意的是,須要將已經遍歷的單詞記錄下來,從而不會發生重複的狀況。spa
//和字典中單詞比較是否能夠轉換 public boolean canTransform(String word1, String word2){ for(int i = 0, count=0 ; i<word1.length() ; i++){ if(word1.charAt(i)!=word2.charAt(i) && ++count>1) return false; } return true; } public int ladderLength(String beginWord, String endWord, List<String> wordList){ Queue<String> q = new LinkedList<String>(); q.add(beginWord); int steps = 0; while(!q.isEmpty()){ int size = q.size(); for(int i = 0 ;i<size ; i++){ String temp = q.poll(); if(temp.equals(endWord)){return steps+1;} for(Iterator<String> iterator = wordList.iterator() ; iterator.hasNext();){ String current = iterator.next(); if(canTransform(current, temp)){ iterator.remove(); q.offer(current); } } } steps++; } return 0; }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~code