[leetcode]Word Ladder II

leetcode上通过率最低的了...

不只要找最短路,还要记录路径

每次遇到记录路径的感觉都好麻烦TT,不太喜欢记录路径...

 

依然是BFS,记录每个的前驱节点father[x],当然这个father有多个

还有个问题就是...如果BFS的话到end肯定有很多路径,那最短的是啥呢?

所以我们采用分层遍历,只要到了end,那么这一层所有的都是最短的(一样长

 

然后用DFS遍历father,从end到start

注意就是DFS在恢复状态的时候一定要考虑完,我之前就是在前面return了但是后面才是恢复状态,导致错误

 

class Solution {
public:
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
          vector<vector<string> >ans;
          if(start == end) return ans;
          unordered_set<string>current , next;
          unordered_set<string> flag;
          unordered_map<string,vector<string> > father;
          
          current.insert(start);

          bool found = false;
         
          while(!current.empty() && !found) {
              //expand
              for(const auto &x : current) {
                  flag.insert(x);
              }
              
              for(auto x : current) {
                  for(int i = 0 ; i < x.size() ; ++i) {
                      for(int j = 'a' ; j <= 'z' ; ++j) {
                          if(x[i] == j) continue;
                          string tmp = x;
                          tmp[i] = j;
                          if(tmp == end) found = true;
                          if(dict.find(tmp) != dict.end() && flag.find(tmp) == flag.end()) {
                              next.insert(tmp);
                              father[tmp].push_back(x);
                          }
                     }
                  }
              }
              //end expand
              
              current.clear();
              swap(current, next);
          }
          //start foudn father
          
          if(found) {
              vector<string> c;
              dfs(ans , father , c , start , end);
          }
          return ans;
    }
private:
    void dfs(vector<vector<string> >&ans, 
             unordered_map<string,vector<string> >& father ,
             vector<string>& c , 
             string& start ,
             string& now) {
                 
        c.push_back(now);
        if(now == start) {
            ans.push_back(c);
            reverse(ans.back().begin() , ans.back().end());
            c.pop_back();
            return;
        }
        auto que = father.find(now) -> second;
        for(auto& x : que) {
            dfs(ans , father , c , start , x);
        }
        c.pop_back();
    }
};

 

你可能感兴趣的:(LeetCode)