zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    ubuntu 安装mysql和redis 开放远程连接
    linux时间不对,执行ntpdate时间同步始终不对。
    Web漏洞
    生产者消费者模型
    多进程抢票问题
    socket通讯-----UDP
    python3读写csv文件
    # 把csv转xls
    python os模块 用资源管理器显示文件,pyinstall打包命令
    创建一个最简单的pyqt5窗口
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854586.html
Copyright © 2011-2022 走看看