Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 1006 Bytes

10.md

File metadata and controls

39 lines (32 loc) · 1006 Bytes
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        
        queue<pair<string,int>>q;
        unordered_set<string>st(wordList.begin(),wordList.end());

        q.push({beginWord,1});
        st.erase(beginWord);

        while(!q.empty())
        {
            string word=q.front().first;
            int step=q.front().second;
            q.pop();

            if(word==endWord)
                return step;

            for(int i=0;i<word.size();i++)
            {
                int org=word[i];
                for(char c='a';c<='z';c++)
                {
                    word[i]=c;
                    if(st.find(word)!=st.end())
                    {
                        st.erase(word);
                        q.push({word,step+1});
                    }
                }
                word[i]=org;
            }
        }
        return 0;
    }