LeetCode //C++ - 126. Word Ladder II

2024-05-27 13:52
文章标签 leetcode c++ ii word 126 ladder

本文主要是介绍LeetCode //C++ - 126. Word Ladder II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

126. Word Ladder II

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s 1 s_1 s1 -> s 2 s_2 s2 -> … -> s k s_k sk such that:

  • Every adjacent pair of words differs by a single letter.
  • Every s i s_i si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • sk == endWord

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s 1 s_1 s1, s 2 s_2 s2, …, s k s_k sk].
 

Example 1:

Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output:[[“hit”,“hot”,“dot”,“dog”,“cog”],[“hit”,“hot”,“lot”,“log”,“cog”]]
Explanation: There are 2 shortest transformation sequences:
“hit” -> “hot” -> “dot” -> “dog” -> “cog”
“hit” -> “hot” -> “lot” -> “log” -> “cog”+

Example 2:

Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
Output:[]
Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.

Constraints:
  • 1 <= beginWord.length <= 5
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 500
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.
  • The sum of all shortest transformation sequences does not exceed 1 0 5 10^5 105.

From: LeetCode
Link: 126. Word Ladder II


Solution:

Ideas:
  • Initialization: An unordered set is used to quickly check if a word is in the dictionary (dict). A queue (q) manages the BFS starting with beginWord.
  • BFS Loop: The BFS iteratively transforms each character of the current word to explore all possible one-letter transformations. If these transformed words are in dict, they’re added to the queue for further exploration. parents keeps track of each word’s predecessors in the path.
  • Backtracking Function: Once the shortest paths are identified (found is true), the buildPaths function reconstructs the paths from endWord to beginWord using the parents map and accumulates them in ladders.
  • Handling Level-wise Exploration: visitedThisLevel prevents revisiting words in the same BFS level, optimizing the search and avoiding redundant paths.
Code:
class Solution {
public:vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {unordered_set<string> dict(wordList.begin(), wordList.end());vector<vector<string>> ladders;unordered_map<string, vector<string>> parents;queue<string> q;q.push(beginWord);bool found = false;while (!q.empty() && !found) {int levelSize = q.size();unordered_set<string> visitedThisLevel; // To handle duplicates in the current BFS levelfor (int i = 0; i < levelSize; ++i) {string currentWord = q.front();q.pop();string originalWord = currentWord; // Save the original word// Transform each character of the word to find all possible transformationsfor (char& ch : currentWord) {char originalChar = ch; // Save the original characterfor (ch = 'a'; ch <= 'z'; ++ch) {if (ch == originalChar) continue;if (dict.find(currentWord) != dict.end()) {if (currentWord == endWord) {found = true;}if (!found && visitedThisLevel.insert(currentWord).second) {q.push(currentWord);}parents[currentWord].push_back(originalWord);}}ch = originalChar; // Restore the original character}}// Remove visited words of this level from the dictionary to prevent going backwards in BFSfor (const string& word : visitedThisLevel) {dict.erase(word);}}if (found) {vector<string> path;buildPaths(endWord, beginWord, parents, path, ladders);}return ladders;}private:void buildPaths(const string& word, const string& beginWord,unordered_map<string, vector<string>>& parents,vector<string>& path, vector<vector<string>>& ladders) {if (word == beginWord) {path.push_back(word);vector<string> currentPath = path;reverse(currentPath.begin(), currentPath.end());ladders.push_back(currentPath);path.pop_back();return;}path.push_back(word);for (const string& parent : parents[word]) {buildPaths(parent, beginWord, parents, path, ladders);}path.pop_back();}
};

这篇关于LeetCode //C++ - 126. Word Ladder II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1007659

相关文章

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

C++ vector的常见用法超详细讲解

《C++vector的常见用法超详细讲解》:本文主要介绍C++vector的常见用法,包括C++中vector容器的定义、初始化方法、访问元素、常用函数及其时间复杂度,通过代码介绍的非常详细,... 目录1、vector的定义2、vector常用初始化方法1、使编程用花括号直接赋值2、使用圆括号赋值3、ve

如何高效移除C++关联容器中的元素

《如何高效移除C++关联容器中的元素》关联容器和顺序容器有着很大不同,关联容器中的元素是按照关键字来保存和访问的,而顺序容器中的元素是按它们在容器中的位置来顺序保存和访问的,本文介绍了如何高效移除C+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++