[Leetcode] Word Ladder 单词爬梯

Word Ladder

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord,
such that:ui

Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example,code

Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"] As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.orm

Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters.rem

广度优先搜索

复杂度

时间 O(N) 空间 O(N)it

思路

由于要求最短路径,若是咱们用深度优先搜索的话必须遍历全部的路径才能肯定哪一个是最短的,而用广度优先搜索的话,一旦搜到目标就能够提早终止了,并且根据广度优先的性质,咱们确定是先经过较短的路径搜到目标。另外,为了不产生环路和重复计算,咱们找到一个存在于字典的新的词时,就要把它从字典中移去。这么作是由于根据广度优先,咱们第一次发现词A的路径必定是从初始词到词A最短的路径,对于其余可能再通过词A的路径,咱们都没有必要再计算了。io

代码

public class Solution {

    public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
        Queue<String> queue = new LinkedList<String>();
        // step用来记录跳数
        int step = 2;
        queue.offer(beginWord);
        while(!queue.isEmpty()){
            int size = queue.size();
            // 控制size来确保一次while循环只计算同一层的节点,有点像二叉树level order遍历
            for(int j = 0; j < size; j++){
               String currWord = queue.poll();
                // 循环这个词从第一位字母到最后一位字母
                for(int i = 0; i < endWord.length(); i++){
                    // 循环这一位被替换成25个其余字母的状况
                    for(char letter = 'a'; letter <= 'z'; letter++){
                        StringBuilder newWord = new StringBuilder(currWord);
                        newWord.setCharAt(i, letter);
                        if(endWord.equals(newWord.toString())){
                            return step;    
                        } else if(wordDict.contains(newWord.toString())){
                            wordDict.remove(newWord.toString());
                            queue.offer(newWord.toString());
                        }
                    }
                } 
            }
            step++;
        }
        return 0;
    }
}
相关文章
相关标签/搜索