• 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;
            
        }
    };
  • 相关阅读:
    应用图标大小
    AndroidStudio使用笔记
    shell 三剑客之 sed 命令详解
    shell 三剑客之 sed pattern 详解
    shell 文本处理三剑客之 grep 和 egrep
    Shell 编程中的常用工具
    shell 函数的高级用法
    shell 数学运算
    shell 变量的高级用法
    nginx 之 https 证书配置
  • 原文地址:https://www.cnblogs.com/wxquare/p/5906160.html
Copyright © 2020-2023  润新知