• 127 Word Ladder


    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 intermediate word must exist in the word list

    For example,

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

    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.

    ====================

    广度优先搜索bfs,

    题目需要注意的地方:

    1. 如果没有可以转变的单词阶梯,需要返回-1,
    2. 所有的单词由相同的长度
    3. 所有的单词都是小写字母
    4. 转换过程中,一次只能转变一个字母
    5. 输入有开始单词,有结束单词,还有一个词典集合set
    6. 转变过程中的所有 中间单词表示  都是从词典集合set中存在的
    7. 输出的是 单词阶梯的长度(包括开始单词结束单词

    经典bfs搜索

    • 定义一个unorder_map<string,int> m;  保存的是在转变过程中的  中间单词出现的位置,即"hit" -> "hot" -> "dot" -> "dog" -> "cog",m[hit]=1,m[hot]=2
    • 定义一个queue<string> q;保存的是在广度优先搜索bfs的搜索次序,因为bfs一定会用到队列,就像深度优先搜索dfs一定会用到栈一样。这个队列q会把搜索路径中所有经过的  单词中间节点  都过滤一边。
    • 因为我们只是求单一的解,找到即结束。所以不用保存搜索路径,不用找到所有的结果。
    • 看代码。
    int ladderLength(string beginWord, string endWord,
                    unordered_set<string>& wordList) {
            unordered_map<string,int> m;
            queue<string> q;
            m[beginWord] = 1;
            q.push(beginWord);
            while(!q.empty()){
                string word = q.front();
                q.pop();
                for(int i = 0;i<(int)word.size();i++){
                    string newWord = word;
                    for(char ch = 'a';ch<='z';++ch){///因为我们每次只能改变一个字母,所以这里是一重循环遍历'a'->'z',看是否能在字典集合中找改变后的 单词值
                        newWord[i] = ch;///这就是改变一个字母后的单词值
                        if(newWord==endWord) return m[word]+1;///此时已经能够找到一条路径了,直接返回就行了。
                        if(wordList.find(newWord)!=wordList.end() && ///在字典集合中存在,
                            m.find(newWord)==m.end()){///改变一个字母后的单词在 哈希表m中不存在,是为了防止出现hit->hit的情形。
                            //cout<<"q.size()="<<q.size()<<endl;
                            //cout<<"word->"<<word<<endl;
                            //cout<<"newWord->"<<newWord<<endl<<endl;
                            q.push(newWord);///放入q中,为bfs做准备
                            m[newWord] = m[word]+1;///新单词在 单词阶梯中的位置
                        }
                    }///for
                }///for
            }
            return 0;
        }
  • 相关阅读:
    长沙雅礼中学集训-------------------day1(内含day0)
    17年 5月份刷题版
    manecher_回文串;
    后缀数组
    湖南集训
    好像又好久没更了;计算课noip模拟赛;
    dp的练习题;
    oj1638
    【noi】植物大战僵尸
    #日常吐槽
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5567803.html
Copyright © 2020-2023  润新知