zoukankan      html  css  js  c++  java
  • Word Ladder

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord 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.
    class Solution {
    public:
        int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
            if(beginWord.size() != endWord.size()) return 0;
            
            unordered_set<string> visited;
            int level = 0;
            bool found = 0;
            queue<string> current,next;
            
            current.push(beginWord);
            while(!current.empty() && !found){
                level++;
                while(!current.empty() && !found){
                    string str(current.front());
                    current.pop();
                    for(size_t i=0;i<str.size();i++){
                        string new_word(str);
                        for (char c = 'a';c <= 'z';c++){
                            if (c == new_word[i]) continue;
                            
                            swap(new_word[i],c);
                            if(new_word == endWord){
                                found = 1;
                                break;
                            }
                            
                            if(wordList.count(new_word) && !visited.count(new_word)){
                                visited.insert(new_word);
                                next.push(new_word);
                            }
                            swap(new_word[i],c);
                        }
                    }
                }
                swap(current,next);
            }
            if(found) return level+1;
            else return 0;
            
        }
    };
  • 相关阅读:
    jquery保存用户名和密码到cookie里面
    avalon框架
    mybatis分页插件
    获取前台查询条件的公用方法
    mybatis分页插件
    maven出错The folder is already a source folder
    Jquery图片上传预览效果
    springMVC文件上传
    自动将String类型的XML解析成实体类
    JavaScript 引擎
  • 原文地址:https://www.cnblogs.com/wxquare/p/5906160.html
Copyright © 2011-2022 走看看