leetcode 127 wordladder

给定一个开头单词beginWord,一个结尾单词endWord,一个单词列表wordList,其中beginWord不在wordList中,而endWord在wordList中,这些单词都是等长的;

一个单词的一次转变表示其中的一个字母改变;所有转变的单词都在wordList中,试求从beginWord到endWord的最短路径长度;没有返回0;

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

广度优先搜索,先找到所有列表中一次能到达的单词,然后根据这些单词找到两次能到达的单词,直到找到为止

class Solution {
public:
    bool judgeOneLetterDiffBetweenTwoWords(string firstword, string secondword){
        int difftime = 0, len1 = firstword.length(), len2 = secondword.length();
        if(len1 != len2){
            return false;
        }
        if(len1 == 0){
            return true;
        }
        char tmp1 = '\0',tmp2 = '\0';
        for(int i=0;i<len1;i++){
            tmp1 = firstword[i];
            tmp2 = secondword[i];
            if(tmp1 != tmp2){
                difftime++;
                if (difftime > 1){
                    return false;
                }
            }
        }
        if(difftime == 1){
            return true;
        }
        return false;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        set<string> set_available(wordList.cbegin(), wordList.cend());
        vector<string> l1, l2;
        int num_ceng = 1;
        string tmp = "", tmp2 = "";
        bool tmp3 = false;
        l1.push_back(beginWord);
        while(!l1.empty() && !set_available.empty()){
            num_ceng++;
            vector<string>::iterator it = l1.begin();
            //遍历该层的单词
            while(it != l1.end()){
                tmp = *it;
                set<string>::iterator set_it = set_available.begin();
                //遍历set
                while(set_it != set_available.end()){
                    tmp2 = *set_it;
                    tmp3 = judgeOneLetterDiffBetweenTwoWords(tmp, tmp2);
                    if (tmp3 == true){
                        if (tmp2 == endWord){
                            return num_ceng;
                        }
                        l2.push_back(tmp2);
                        set_it = set_available.erase(set_it);
                    }else{
                        set_it++;
                    }
                }
                it++;
            }
            // l1 = l2;
            swap(l1, l2);
            l2.clear();
        }
        return 0;
    }
};

算法复杂度O(N^2)打败了10%的人,感觉有待改进的地方

 

posted @ 2019-06-11 10:02  茫茫碧落  阅读(190)  评论(0编辑  收藏  举报