生活随笔
收集整理的這篇文章主要介紹了
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();q
.pop();if(frontPath
.size() > level
){for(string word
:words
) wlist
.erase(word
);words
.clear();level
= frontPath
.size();if(level
> minLevel
) 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
);newPath
= frontPath
;newPath
.push_back(newLastWord
);if(newLastWord
== endWord
){ans
.push_back(newPath
);minLevel
= level
;}elseq
.push(newPath
);}}}}return ans
;}
};
總結
以上是生活随笔為你收集整理的LeetCode 126. 单词接龙 II(图的BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。