leetcode[126]Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:

     All words have the same length.

     All words contain only lowercase alphabetic characters.

class Solution {
public:
void dfs(vector<vector<string>> &res,vector<string> str,unordered_map<string,vector<string>> &father,string start, string now)
{
    if(now==start)
    {
        str.push_back(now);
        res.push_back(str);
        reverse(res.back().begin(),res.back().end());
        return;
    }
    for(const auto &x : father[now])
    {
        str.push_back(now);
        dfs(res,str,father,start,x);
        str.pop_back();
    }
}
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        vector<vector<string>> res;
        if(start==end)return res;
        unordered_set<string> curr,next;
        unordered_set<string> all;
        unordered_map<string,vector<string>> father;
        bool found=false;
        curr.insert(start);
        while(!curr.empty()&&!found)
        {
            for(const auto &x : curr)
            {
                all.insert(x);
            }
            for(const auto &x : curr)
            {
                for(int i=0;i<x.length();i++)
                {
                    for(char j='a';j<='z';j++)
                    {
                        if(x[i]==char(j))continue;
                        string tx=x;
                        tx[i]=char(j);
                        if(tx==end)found=true;
                        if(dict.find(tx)!=dict.end()&&all.find(tx)==all.end())
                        {
                            next.insert(tx);
                            father[tx].push_back(x);
                        }
                    }
                }
            }
            curr.clear();
            swap(curr,next);
        }
        vector<string> str;
        dfs(res,str,father,start,end);
    }
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281272.html