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.


Solution:

class Solution {
public:
    vector<vector<string>> res;

    void dfsPath(unordered_map<string, unordered_set<string>> &path, vector<string> &temp, const string &key)
    {
        if(path[key].size() == 0)
        {
            temp.push_back(key);
            vector<string> tempPath = temp;
            reverse(tempPath.begin(), tempPath.end());
            res.push_back(tempPath);
            temp.pop_back();
            return ;
        }

        temp.push_back(key);
        for(unordered_set<string>::iterator iter = path[key].begin(); iter != path[key].end(); ++iter)
        {
            dfsPath(path, temp, *iter);
        }
        temp.pop_back();
    }

    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        res.clear();
        unordered_set<string> current;
        unordered_set<string> next;
        unordered_map<string, unordered_set<string>> path;

        if(dict.count(start) > 0) dict.erase(start);
        current.insert(start);

        while(current.count(end) == 0 && !dict.empty())
        {
            for(unordered_set<string>::iterator iter = current.begin(); iter != current.end(); ++iter)
            {
                string str = *iter;
                for(int i = 0; i < str.length(); ++i)
                {
                    for(char c = 'a'; c <= 'z'; ++c)
                    {
                        string tmp = str;
                        if(tmp[i] == c) continue;
                        tmp[i] = c;
                        if(dict.count(tmp) > 0)
                        {
                            path[tmp].insert(str);
                            next.insert(tmp);
                        }
                    }
                }
            }

            if(next.empty()) break;
            for(unordered_set<string>::iterator iter = next.begin(); iter != next.end(); ++iter)
            {
                dict.erase(*iter);
            }

            current = next;
            next.clear();
        }

        vector<string> temp;
        if(current.count(end) > 0) dfsPath(path, temp, end);

        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值