【剑斩OFFER】算法的暴力美学——力扣 127 题:单词接龙

一、题目描述

二、算法原理

思路:跟边权为 1 的最短路径一样,使用 BFS 算法就能解决

https://blog.csdn.net/2403_84958571/article/details/157183596?spm=1011.2415.3001.10575&sharefrom=mp_manage_link

三、代码实现

cpp 复制代码
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {

        unordered_set<string> hash_w(wordList.begin(),wordList.end());//单词库
        unordered_set<string> hash_b;
        hash_b.insert(beginWord);//防止遍历过

        queue<string> que;//使用队列实现 BFS 
        que.push(beginWord);

        int count = 1;//记录最短实现的步骤

        while(que.size())
        {
            int qor = que.size();
            count++;//每层都会有个变化的单词
            while(qor--)
            {
                string tmp = que.front();
                que.pop();
                for(int i = 0; i < tmp.size(); i++)
                {
                    for(char k = 'a'; k <= 'z'; k++)//枚举各种可能
                    {
                        string tmp_str = tmp;
                        tmp_str[i] = k;
                        if(!hash_b.count(tmp_str) && hash_w.count(tmp_str))//让下一个层进入
                        {
                            que.push(tmp_str);
                            hash_b.insert(tmp_str);
                            if(tmp_str == endWord) return count;
                        }
                    }
                }
            }
        }

        //无法演化到 endword
        return 0;

    }
};
相关推荐
TsingtaoAI6 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet6 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件7 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病7 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap9 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语9 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet9 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_10 小时前
rog_map参数理解
算法
春日见10 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
叩码以求索11 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法