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

    }
};
相关推荐
地平线开发者2 小时前
【模型轻量化专题】衡量模型轻量性的指标
算法
学习星球5 小时前
OFDM技术精讲:正交性推导、循环前缀原理与80行Python链路仿真(附实测数据)
算法·面试·前端框架
alphaTao11 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
Interview Aid11212 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
顶点多余21 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
罗西的思考1 天前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha60161 天前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘1 天前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天1 天前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
AI情绪识别开源1 天前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang