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++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、

Java使用POI-TL和JFreeChart动态生成Word报告

《Java使用POI-TL和JFreeChart动态生成Word报告》本文介绍了使用POI-TL和JFreeChart生成包含动态数据和图表的Word报告的方法,并分享了实际开发中的踩坑经验,通过代码... 目录前言一、需求背景二、方案分析三、 POI-TL + JFreeChart 实现3.1 Maven

使用C/C++调用libcurl调试消息的方式

《使用C/C++调用libcurl调试消息的方式》在使用C/C++调用libcurl进行HTTP请求时,有时我们需要查看请求的/应答消息的内容(包括请求头和请求体)以方便调试,libcurl提供了多种... 目录1. libcurl 调试工具简介2. 输出请求消息使用 CURLOPT_VERBOSE使用 C

C++实现获取本机MAC地址与IP地址

《C++实现获取本机MAC地址与IP地址》这篇文章主要为大家详细介绍了C++实现获取本机MAC地址与IP地址的两种方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 实际工作中,项目上常常需要获取本机的IP地址和MAC地址,在此使用两种方案获取1.MFC中获取IP和MAC地址获取