zoukankan      html  css  js  c++  java
  • [leetcode-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:
    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.

    思路:

    学习别人的都是用的BFS,参考别人的代码,目前是超时的状态。。。先放在这儿,记录一下。

     int ladderLength(string beginWord, string endWord, vector<string>& wordList)
     {
         bool flag = false;
         for(int j =0;j<wordList.size();j++) //保证endWord出现在wordList里
         {
             if(wordList[j] == endWord) flag = true;
         }
         if(!flag) return 0;
         queue<string> que;
         que.push(beginWord);
         int length = beginWord.size();
         int count = 1, level = 0;
         string str;
         while(!que.empty())
         {
             str = que.front();
             que.pop();
             for(int i = 0;i<length;i++)//每一个字符str[i]挨个替换
             {
                 for(char ch = 'a';ch<='z';ch++)
                 {
                     if(ch == str[i]) continue;//相同
                     swap(str[i],ch);
                     if(str ==endWord) return level+2;
                     for(int j =0;j<wordList.size();j++)
                     {
                         if(wordList[j] == str)
                         {
                             que.push(str);
                             wordList.erase(wordList.begin()+j);
                             break;
                         }
                     }
                      swap(str[i],ch);
                 }
             }
                count--;
             if(count == 0)
             {
                 count = que.size();
                 level++;
             }
         }
        return 0;
    }

    参考:

    http://blog.csdn.net/u012462822/article/details/51065951

  • 相关阅读:
    狼文化的一点思考
    数据可视化之风向图
    谈谈JavaScript代码混淆
    比尔盖茨2016好书推荐
    Cesium原理篇:glTF
    个人 产品 团队(下):个人与团队
    技术 产品 团队(上):如何成为超级个体
    惊艳的HTML5动画特效及源码
    精心挑选的HTML5/CSS3应用及源码
    炫酷霸气的HTML5/jQuery应用及源码
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6792429.html
Copyright © 2011-2022 走看看