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

    }
};
相关推荐
BothSavage18 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn18 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽20 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰2 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六2 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术2 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize2 天前
初识DFS 与 BFS:递归、队列与图遍历
算法