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;
        }
    };
  • 相关阅读:
    PHP $_POST 变量
    PHP $_GET 变量
    PHP 完整表单实例
    PHP 表单
    PHP 表单
    PHP 表单验证
    00_前情回顾
    18_今日回顾
    VMware 12PRO安装Mac OS X 10.10.5
    05_传智播客iOS视频教程_第一个OC程序
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281269.html
Copyright © 2011-2022 走看看