[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;
    }
}
相關文章
相關標籤/搜索