Word Ladder 单词台阶

来源:互联网 发布:单片机新颖毕业设计 编辑:程序博客网 时间:2024/05/16 02:03
class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        unordered_map<string,string> father;
        unordered_set<string> isvisited;
        queue<string> current,next;
        bool found=false;
        int level=0;
        current.push(start);
        while(!current.empty()&&!found)
        {
            level++;
            while(!current.empty()&&!found)
            {  
               string str=current.front();
               current.pop();
               for(int i=0;i<str.size();i++)
               {
                  string newword(str);
                  for(char c='a';c<='z';c++)
                  {
                      if(c==newword[i]) 
                      continue;
                      swap(c,newword[i]);
                      if(newword==end)
                      {
                          father[newword]=str;
                          found=true;
                          break;
                      }
                      if(dict.count(newword)>0&&!isvisited.count(newword))
                      {
                          
                          father[newword]=str;
                          next.push(newword);
                          isvisited.insert(newword);
                      }
                      swap(newword[i],c);
                  }
               }
           }
           swap(next,current);
    }
    if(found) return level+1;
    else return 0;
    }
};
0 0
原创粉丝点击