Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Note:
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
class Solution {
private:
bool isNeighbor(string& a, string& b) {
int cnt = 0;
for(int i = 0; a[i]; i++) {
if(a[i] != b[i])
cnt++;
}
return cnt == 1;
}
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
queue<string> cur;
queue<string> next;
cur.push(beginWord);
int step = 2;
while(cur.size()) {
string tmp = cur.front();
cur.pop();
for(auto& it : wordList) {
if(it == "" || !isNeighbor(it, tmp))
continue;
if(it == endWord)
return step;
next.push(it);
it = "";
}
if(cur.empty()){
step++;
swap(cur, next);
}
}
return 0;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有