127. Word Ladder 2

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        int dist=2;
        unordered_set<string> head,tail,*phead,*ptail;
        head.insert(beginWord);
        tail.insert(endWord);
        while(!head.empty()&&!tail.empty())
        {
            if(head.size()<=tail.size())//phead指向较小的set ptail指向较大的set
            {
                phead=&head;
                ptail=&tail;
            }
            else
            {
                phead=&tail;
                ptail=&head;
            }

            unordered_set<string> temp;
            for(auto it=phead->begin();it!=phead->end();it++)//遍历phead中所有元素
            {
                wordList.erase(*it);

                string word=*it;
                for(int i=0;i//对于每个元素的所有可能位置尝试只改变一个变量的
                {

                    char letter=word[i];
                    for(int j=0;j<26;j++)
                    {
                        word[i]='a'+j;
                        if(ptail->find(word)!=ptail->end())//在ptail中查找到
                            return dist;
                        if(wordList.find(word)!=wordList.end())
                        {
                            wordList.erase(word);
                            temp.insert(word);
                        }
                    }
                    word[i]=letter;
                }

            }
            swap(*phead,temp);
            dist++;
        }
        return 0;
    }
};

你可能感兴趣的:(图,数据结构)