博客
关于我
126. 单词接龙 II
阅读量:563 次
发布时间:2019-03-09

本文共 1791 字,大约阅读时间需要 5 分钟。

为了解决从 beginWord 到 endWord 的最短转换序列问题,我们可以使用广度优先搜索(BFS)来找到所有可能的最短路径。每次转换只能改变一个字母,并且中间单词必须在给定的字典中。

方法思路

  • 预处理:首先,检查所有单词的长度是否一致。如果不一致,直接返回空列表。
  • 构建字典映射:使用哈希表(字典)存储单词及其对应的位置,以便快速查找。
  • BFS初始化:从 beginWord 开始,加入队列,并记录为已访问。
  • BFS遍历:在每一步中,生成所有可能的变换单词(每个字母都可以变成其他25个字母),并检查这些变换是否在字典中且未被访问过。如果是,将它们加入队列。
  • 记录路径:当找到 endWord 时,记录路径并继续搜索,直到队列为空,确保找到所有可能的最短路径。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;vector
    > findLadders(string beginWord, string endWord, vector
    wordList) { int n = beginWord.size(); // 检查所有单词长度是否一致 for (const string& word : wordList) { if (word.size() != n) { return {}; } } unordered_map
    wordId; for (int i = 0; i < wordList.size(); ++i) { wordId[wordList[i]] = i; } // 检查beginWord和endWord是否在字典中 if (wordId.find(beginWord) == wordId.end() || wordId.find(endWord) == wordId.end()) { return {}; } queue
    > q; unordered_set
    visited; vector
    > result; q.push({beginWord, 0}); visited.insert(beginWord); while (!q.empty()) { auto current = q.front(); q.pop(); string currentWord = current.first; int steps = current.second; if (currentWord == endWord) { result.push_back({currentWord}); continue; // 继续搜索可能的其他路径 } for (int i = 0; i < currentWord.size(); ++i) { char c = currentWord[i]; for (char ch = 'a'; ch <= 'z'; ++ch) { if (ch == c) continue; string newWord = currentWord; newWord[i] = ch; // 检查新单词是否在字典中且未被访问过 if (wordId.find(newWord) != wordId.end() && !visited.count(newWord)) { visited.insert(newWord); q.push({newWord, steps + 1}); } } } } return result;}

    代码解释

  • 预处理:检查所有单词的长度是否一致,确保转换过程中的单词长度保持一致。
  • 字典映射:使用 unordered_map 记录每个单词的位置,以便快速查找。
  • BFS初始化:从 beginWord 开始,初始化队列和已访问集合。
  • BFS遍历:生成所有可能的变换单词,检查是否在字典中,未被访问过,并加入队列。
  • 路径记录:每当找到 endWord 时,记录路径并继续搜索,确保找到所有可能的最短路径。
  • 这样,BFS算法能够高效地找到所有最短转换序列,确保中间单词都在字典中。

    转载地址:http://rcnpz.baihongyu.com/

    你可能感兴趣的文章
    Python3连接MySQL
    查看>>
    Python关于isinstance函数的解析 | 附Demo(全)
    查看>>
    Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
    查看>>
    python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
    查看>>
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>
    Python: Range() 最大尺寸;动态的还是静态的?
    查看>>
    Python: Windows下用 multiprocessing 的深坑
    查看>>
    python:Could not find platform independent libraries <prefix>解决方法
    查看>>
    Python:datetime tzinfo 时区名称文档
    查看>>
    Python:deepcopy(list) vs new_list = old_list[:]
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
    查看>>
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>
    python:从列表中创建元组列表
    查看>>
    Python:从嵌套列表中删除重复项
    查看>>
    Python:从间隔映射到值
    查看>>