日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 126. 单词接龙 II(图的BFS)

發布時間:2024/7/5 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 126. 单词接龙 II(图的BFS) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 題目

給定兩個單詞(beginWord 和 endWord)和一個字典 wordList,找出所有從 beginWord 到 endWord 的最短轉換序列。

轉換需遵循如下規則:

  • 每次轉換只能改變一個字母。
  • 轉換過程中的中間單詞必須是字典中的單詞。

說明:
如果不存在這樣的轉換序列,返回一個空列表。
所有單詞具有相同的長度。
所有單詞只由小寫字母組成。
字典中不存在重復的單詞。
你可以假設 beginWord 和 endWord 是非空的,且二者不相同。

示例 1: 輸入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 輸出: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"] ]示例 2: 輸入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] 輸出: [] 解釋: endWord "cog" 不在字典中,所以不存在符合要求的轉換序列。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/word-ladder-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

類似題目:
LeetCode 127. 單詞接龍(圖的BFS/雙向BFS)
程序員面試金典 - 面試題 17.22. 單詞轉換(BFS)

2. BFS解題

  • 詳見注釋
class Solution { public:vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {vector<vector<string>> ans;unordered_set<string> wlist(wordList.begin(),wordList.end());unordered_set<string> words;//存放當次被加入到路徑的單詞queue<vector<string>> q;//隊列里存放的是可行的路徑q.push({beginWord});words.insert(beginWord);int level = 1, minLevel = INT_MAX, n, i;vector<string> frontPath, newPath;string lastWordOfPath, newLastWord;char ch;while(!q.empty()){n = q.size();while(n--){frontPath = q.front();//vector<string>q.pop();//frontPath出隊if(frontPath.size() > level)//下一個level時進入{for(string word:words) wlist.erase(word);//將上一個lv進入路徑的單詞從集合中刪除words.clear();level = frontPath.size();//level+1if(level > minLevel) //如果level比最小的還大,沒必要進行下去break;}lastWordOfPath = frontPath.back();for(i = 0; i < lastWordOfPath.size(); i++){ //根據最后一個單詞衍生新的單詞newLastWord = lastWordOfPath;for(ch = 'a'; ch <= 'z'; ch++){newLastWord[i] = ch;if(!wlist.count(newLastWord)) //新單詞不在集合中,下一個continue;words.insert(newLastWord);//在集合中,加入路徑,并記錄在wordsnewPath = frontPath;//vector<string>newPath.push_back(newLastWord);if(newLastWord == endWord){ans.push_back(newPath);minLevel = level;}elseq.push(newPath);}}}}return ans;} };

總結

以上是生活随笔為你收集整理的LeetCode 126. 单词接龙 II(图的BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。