leetcode127. Word Ladder

题目要求

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;
     }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~code

相关文章
相关标签/搜索