【leetcode】 word ladder

    xiaoxiao2021-03-25  126

    问题:

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord 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.

    UPDATE (2017/1/20): The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

    分析:

    1、BFS,解题思路可见http://www.cnblogs.com/ShaneZhang/p/3748494.html;

    2、leetcode在2017.1.20更新了word ladder这道题,将wordlist从unordered_set改为vector类型

    (作为一枚编程菜鸟,我在程序中又将vector改回unordered_set类型了。。。)

    3、欢迎指正!

    代码:

    class Solution { public:     int ladderLength(string beginWord, string endWord, vector<string>& DictList) {        unordered_set<string> DictSet;        for(string w:DictList){            DictSet.insert(w);        }        queue<string> toVisit;        addNextWord(beginWord,DictSet,toVisit);        int dist=2;        //BFS遍历        while(!toVisit.empty()){            int n=toVisit.size();            //看当前单词的邻居中            for(int j=0;j<n;j++){                string word=toVisit.front();                toVisit.pop();                //若有endWord,则返回距离                if(word==endWord) return dist;                //将当前单词的邻居的邻居放入队列中                addNextWord(word,DictSet,toVisit);            }            //当前词典的邻居都无endWord,则这一层遍历结束;故BFS深度加一            dist++;        }        //BFS遍历结束,还未找到endWord,则无法构成transform        return 0;     } private:     void addNextWord(string& word,unordered_set<string>& Dict,queue<string>& toVisit){        //当前单词从词典dict中删去         Dict.erase(word);         for(int p=0;p<word.length();p++){             char letter=word[p];             for(int i=0;i<26;i++){                 word[p]='a'+i;                 if(Dict.find(word)!=Dict.end()){                     //当前单词的邻居从词典中删去,并放入待访问的队列中                     Dict.erase(word);                     toVisit.push(word);                 }             }             //每次只改变一个字符             word[p]=letter;         }     } };

    转载请注明原文地址: https://ju.6miu.com/read-3823.html

    最新回复(0)