Word Ladder II 单词台阶II,求路径

来源:互联网 发布:知乎 鬼吹灯 编辑:程序博客网 时间:2024/06/05 07:45
class Solution {
public:
    void generatepath(unordered_map<string,vector<string>>&father,string start,string word,vector<string> &path,vector<vector<string>>&result)
    {  
        path.push_back(word);
        if(word==start)
        {
            result.push_back(path);
            reverse(result.back().begin(),result.back().end());
        }
        else
        {
            for(auto f:father[word])
            generatepath(father,start,f,path,result);
        }
        path.pop_back();
    }
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
      unordered_set<string> current,next;
      unordered_map<string,vector<string>> father;
      unordered_set<string> visited;
      bool found=false;
      current.insert(start);
      while(!current.empty()&&!found)
      {
          for(auto iter=current.begin();iter!=current.end();iter++)
          {
              visited.insert(*iter);
          }
          for(auto iter=current.begin();iter!=current.end();iter++)
          {   
              for(int i=0;i<iter->size();i++)
              {
              string word=*iter;
              for(char c='a';c<='z';c++)
              {
                  if(c==word[i])
                  continue;
                  swap(c,word[i]);
                  if(word==end)
                  found=true;
                  if(visited.count(word)==0&&dict.count(word)>0||word==end)
                  {
                      father[word].push_back(*iter);
                      next.insert(word);
                  }
                  swap(c,word[i]);
              }
              }
          }
          current.clear();
          swap(next,current);
      }
      vector<vector<string>> result;
      if(found)
      {
         vector<string> path;
          generatepath(father,start,end,path,result);
      }
      return result;
    }
};
0 0
原创粉丝点击