zoukankan      html  css  js  c++  java
  • leetcode[127]Word Ladder

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

    1. Only one letter can be changed at a time
    2. Each intermediate word must exist in the dictionary

    For example,

    Given:
    start = "hit"
    end = "cog"
    dict = ["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 start, string end, unordered_set<string> &dict) {
            unordered_set<string> add;
            add.insert(start);
            queue<string> q;
            q.push(start);
            int res=0;
            int levCurr=1,levNext=0;
            while(!q.empty())
            {
                string s0=q.front();
                q.pop();
                levCurr--;
                for(int i=0;i<s0.size();i++)
                {
                    for(char j='a';j<='z';j++)
                    {
                        if(s0[i]==char(j))continue;
                        string s=s0;
                        s[i]=char(j);
                        if(s==end)return res+2;
                        if(dict.find(s)!=dict.end()&&add.find(s)==add.end())
                        {
                            add.insert(s);
                            q.push(s);
                            levNext++;
                        }
                    }
                }
                if(levCurr==0)
                {
                    levCurr=levNext;
                    levNext=0;
                    res++;
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    leetcode题库
    递归的存储以及执行顺序
    linux与开发板串口通信
    opencv基础到进阶(2)
    opencv基础到进阶(1)
    js的搜索遍历精讲
    js闭包深度讲解
    js使用for in遍历时的细节问题
    分分钟解决正则表达式
    css3中的新特性经典应用
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281269.html
Copyright © 2011-2022 走看看