【剑斩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;

    }
};
相关推荐
丷丩8 小时前
三级缓存下MVT地图瓦片服务性能优化策略
算法·缓存·性能优化·gis·geoai-up
m0_629494738 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
ʚ希希ɞ ྀ9 小时前
单词拆分----dp
算法
智者知已应修善业10 小时前
【51单片机LED闪烁10次数码管显示0-9】2023-12-14
c++·经验分享·笔记·算法·51单片机
智者知已应修善业10 小时前
【51单片机2按键控制1个敞亮LED灯闪烁和熄灭】2023-11-3
c++·经验分享·笔记·算法·51单片机
AI算法沐枫10 小时前
大模型 | 大模型之机器学习基本理论
人工智能·python·神经网络·学习·算法·机器学习·计算机视觉
吃着火锅x唱着歌10 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
凌波粒11 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
paeamecium11 小时前
【PAT甲级真题】- A+B in Hogwarts
c++·算法·pat考试·pat