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,那么遍历终止,将当前遍历的次数返回。这里要注意的是,需要将已经遍历的单词记录下来,从而不会发生重复的情况。

代码

    //和字典中单词比较是否可以转换
    public boolean canTransform(String word1, String word2){
         for(int i = 0, count=0 ; i1) return false;
         }
         return true;
     }
     
     public int ladderLength(String beginWord, String endWord, List wordList){
         Queue q = new LinkedList();
         q.add(beginWord);
         int steps = 0;
         while(!q.isEmpty()){
             int size = q.size();
             for(int i = 0 ;i iterator = wordList.iterator() ; iterator.hasNext();){
                     String current = iterator.next();
                     if(canTransform(current, temp)){
                         iterator.remove();
                         q.offer(current);
                     }
                 }
             }
            steps++;

         }
         return 0;
     }

leetcode127. Word Ladder_第1张图片
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

你可能感兴趣的:(leetcode,java,bfs,queue)