Leetcode 127. Word Ladder

题目大意

给定一个起点单词beginWord,一个终点单词endWord,和一个单词列表wordList,起点单词、终点单词和单词列表中的单词均具有相同的长度。

求从起点单词变化到终点单词的最小过程所涉及的单词数,每次变化可以更改单词的一个字母,并且要求中间过程出现的单词必须出现在单词列表中。

解题思路

使用BFS,从当前单词生成所有可能的下一步,如果下一步单词恰好是终点单词,则返回结果;如果下一步单词在单词列表中,则将其加到BFS的下一层。

注意每个被加入到BFS生成的单词都必须从单词列表中去除,否则会形成循环。

源代码

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        if (beginWord == endWord) return 0;

        wordList.insert(endWord);

        int counter = 0;
        queue<string> que;
        que.push(beginWord);
        que.push("");

        string tmp;

        while (!que.empty()) {
            tmp = que.front();
            que.pop();

            if (tmp == "" && !que.empty()) {
                que.push("");
                counter++;
                continue;
            }

            if (tmp == endWord) {
                return counter + 1;
            }

            vector<string> deprecated;

            for (int ind = 0; ind < tmp.size(); ind++) {
                char ch = tmp[ind];
                for (int k = 0; k < 26; k++) {
                    tmp[ind] = 'a' + k;
                    if (wordList.find(tmp) != wordList.end()) {
                        que.push(tmp);
                        deprecated.push_back(tmp);
                    }
                }
                tmp[ind] = ch;
            }

            for (int ind = 0; ind < deprecated.size(); ind++) {
                wordList.erase(deprecated[ind]);
            }

        }

        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值