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)