• 127. Word Ladder (Tree, Queue; WFS)


    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.

    思路:

    Step1:把本题看成是树状结构

    Step2:通过两个队列,实现层次搜索

    class Solution {
    public:
        int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
            queue<string> queue_to_push;
            queue<string> queue_to_pop;
            bool endFlag = false;
            string curStr;
            int level = 1;
            char tmp;
            
            queue_to_pop.push(beginWord);
            wordList.erase(beginWord); //if beginWord is in the dict, it should be erased to ensure shortest path
            while(!queue_to_pop.empty()){
                curStr = queue_to_pop.front();
                queue_to_pop.pop();
                
                //find one letter transformation
                for(int i = 0; i < curStr.length(); i++){ //traverse each letter in the word
                    for(int j = 'a'; j <= 'z'; j++){ //traverse letters to replace
                        if(curStr[i]==j) continue; //ignore itself
                        tmp = curStr[i];
                        curStr[i]=j;
                        if(curStr == endWord){
                            return level+1;
                        }
                        else if(wordList.count(curStr)>0){ //occur in the dict
                            queue_to_push.push(curStr);
                            wordList.erase(curStr);
                        }
                        curStr[i] = tmp; //back track
                    }
                }
                
                if(queue_to_pop.empty()){//move to next level
                    swap(queue_to_pop, queue_to_push); 
                    level++;
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    【C#】调度程序进程已挂起,但消息仍在处理中;
    【WCF】wcf不支持的返回类型
    power design教程
    C# 动态修改Config
    【C#】delegate(委托) 将方法作为参数在类class 之间传递
    【.NET】Nuget包,把自己的dll放在云端
    【C#】C# 队列,
    【Chrome】新建Chrome插件,新建,事件行为,本地存储
    【IIS】iis6.1下添加两个ftp站点,
    【Jquery】$.Deferred 对象
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854586.html
Copyright © 2020-2023  润新知