Word Ladder II [leetcode]

本题有几个注意点:

1. 回溯找路径时,根据路径的最大长度控制回溯深度

2. BFS时,在找到end单词后,给当前层做标记find=true,遍历完当前层后结束。不需要遍历下一层了。

3. 可以将字典中的单词删除,替代visited的set,这样优化以后时间从1700ms+降到800ms+

代码如下:

class Solution {
public:
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        set<string> queue[2];
        queue[0].insert(start);
        vector<vector<string>> res;
        bool find = false;
        int length = 1;
        bool cur = false;
        map<string, set<string>> mapping;
        
        //bfs
        while (queue[cur].size() && !find)
        {
            length++;
            for (set<string>::iterator i = queue[cur].begin(); i != queue[cur].end(); i++)//delete from dictionary
                dict.erase(*i);
            for (set<string>::iterator i = queue[cur].begin(); i != queue[cur].end(); i++)
            {
                for (int l = 0; l < (*i).size(); l++)
                {
                    string word = *i;
                    for (char c = 'a'; c <= 'z'; c++)
                    {
                        word[l] = c;
                        if (dict.find(word) != dict.end())
                        {
                            if (mapping.find(word) == mapping.end()) mapping[word] = set<string>();
                            mapping[word].insert(*i);
                            if (word == end) find = true;
                            else             queue[!cur].insert(word);
                        }
                    }
                }
            }
            queue[cur].clear();
            cur = !cur;
        }
        if (find)
        {
            vector<string> temp;
            temp.push_back(end);
            getRes(mapping, res, temp, start, length);
        }
        
        return res;
    }
    
    void getRes(map<string, set<string>> & mapping, vector<vector<string>> & res, vector<string> temp, string start, int length)
    {
        if (temp[0] == start)
        {
            res.push_back(temp);
            return;
        }
        if (length == 1) return;//recursion depth
        string word = temp[0];
        temp.insert(temp.begin(), "");
        for (set<string>::iterator j = mapping[word].begin(); j != mapping[word].end(); j++)
        {
            temp[0] = *j;
            getRes(mapping, res, temp, start, length - 1);
        }
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值