LeetCode 127. Word Ladder word Solitaire (C ++ / Java)

topic:

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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWordis not a transformed word.

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.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

analysis:

Given the starting and ending two words, and a list of words, requires us to use the word list to connect the start and end of words, the rule is to require the connection of a time to change a character, and there in the list, termination word in the list is also required.

We can use breadth-first search, from the beginning of words, each character in turn will change from a to z, if the changed word in the list, it is recorded, and the words in the collection, the aim is to to prevent duplicate search, for example, dog-dop-dog, this is a waste of time, when a new word is added and the final word is the same, the number of returns to the step, if the save set word Search (queue) is empty, proved search has ended, and did not find, you can return 0.

You can also use two-way breadth-first search is optimized, while the idea is to start the search from the start word and end word, but also by changing the characters, and in the word list will be added to two centralized search, when the search out of the side of the word, in search word on the other side of the focus, which means appear to understand. As for the order of the search, if the number when one set of words is smaller than the other, it is a priority to start the search from a small number of sets.

program:

C++

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        //set<string> dict;
        unordered_set<string> dict;
        for(string s:wordList)
            dict.insert(s);
        if(dict.count(endWord) == 0)
            return 0;
        queue<string> q;
        q.push(beginWord);
        int l = beginWord.length();
        int step = 0;
        while(!q.empty()){
            step++;
            int len = q.size();
            for(int i = 0; i < len; ++i){
                string word = q.front();
                q.pop();
                for(int j = 0; j < l; ++j){
                    char ch = word[j];
                    for(int k = 'a'; k <= 'z'; ++k){
                        if(k == ch)
                            continue;
                        word[j] = k;
                        if(word == endWord)
                            return step+1;
                        if(dict.count(word) == 0)
                            continue;
                        q.push(word);
                        dict.erase(word);
                    }
                    word[j] = ch;
                }
            }
        }
        return 0;
    }
};
//Bidirectional BFS
//Runtime: 28 ms, faster than 98.16% of C++ online submissions for Word Ladder.
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        //set<string> dict;
        unordered_set<string> dict;
        for(string s:wordList)
            dict.insert(s);
        if(dict.count(endWord) == 0)
            return 0;
        unordered_set<string> q1;
        unordered_set<string> q2;
        q1.insert(beginWord);
        q2.insert(endWord);
        int l = beginWord.length();
        int step = 0;
        while(!q1.empty() && !q2.empty()){
            step++;
            if(q1.size() > q2.size())
                swap(q1, q2); 
            unordered_set<string> q;
            for(string word:q1){
                for(int j = 0; j < l; ++j){
                    char ch = word[j];
                    for(int k = 'a'; k <= 'z'; ++k){
                        if(k == ch)
                            continue;
                        word[j] = k;
                        if(q2.count(word))
                            return step+1;
                        if(dict.count(word) == 0)
                            continue;
                        q.insert(word);
                        dict.erase(word);
                    }
                    word[j] = ch;
                }
            }
            swap(q, q1);
        }
        return 0;
    }
};

Java

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> dict = new HashSet<>(wordList);
        if(!dict.contains(endWord))
            return 0;
        Queue<String> q = new ArrayDeque<>();
        q.offer(beginWord);
        int l = beginWord.length();
        int step = 0;
        while(!q.isEmpty()){
            step++;
            int len = q.size();
            for(int i = 0; i < len; ++i){
                //String word = q.poll();
                StringBuilder word = new StringBuilder(q.poll());
                for(int j = 0; j < l; ++j){
                    char ch = word.charAt(j);
                    for(int k = 'a'; k < 'z'; ++k){
                        if(ch == k)
                            continue;
                        wordsetCharAt (j, ( char ) k);
                        String w = word.toString();
                        if(w.equals(endWord))
                            return step+1;
                        if(!dict.contains(w))
                            continue;
                        q.offer(w);
                        dict.remove(w);
                    }
                    word.setCharAt(j, ch);
                }
            }
        }
        return 0;
    }
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/12324111.html