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;
            
        }
    };
  • 相关阅读:
    组合模式
    C#+ArcEngine中com对象的释放问题
    备忘录模式
    C#中的DataSet添加DataTable问题
    jenkins从节点
    jenkins Publish over SSH
    jenkins凭据
    jenkins maven项目
    jenkins部署-docker
    zabbix api
  • 原文地址:https://www.cnblogs.com/wxquare/p/5906160.html
Copyright © 2011-2022 走看看