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:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
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.
方法1:邻接图,用广度搜索实现
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
set<string> wordSet(wordList.begin(),wordList.end());
queue<pair<string,int>> que;
que.push(make_pair(beginWord,1));
while(!que.empty()){
auto tp=que.front();
que.pop();
if(tp.first==endWord) return tp.second;
for(int i=0;i<tp.first.size();i++){
string cur=tp.first;
for(int j=0;j<26;j++){
cur[i]='a'+j;
auto itrFind=wordSet.find(cur);
if(itrFind!=wordSet.end()){
que.push(make_pair(cur,tp.second+1));
wordSet.erase(itrFind);
}
}
}
}
return 0;
}
};
tips:
1.set是用红黑树实现的,搜索速度比vector的搜索速度快很多,所以先用vector初始化set
set<string> wordSet(wordList.begin(),wordList.end());
unordered_set使用hash表实现的,速度比set更快,在查找多且不需要排序的情况下用unordered_set
2.查找方法有两种,泛型算法,容器自带的算法
find(test.begin().test.end(),word):使用于顺序容易和乱序容器
乱序容器自带的 wordList.find(word)速度更快,利用了set的红黑树查找
总结:乱序容器直接用.find() 顺序容器用find(.begin(), .end(), word);
2.queue<pair<string,int>> que;
que.push(make_pair("aaa",1));
队列添加.push,队列获取最前最后的元素.front(), .end(), 队列pop出第一个元素.pop()
写法2:写法1利用queue实现,把找到的元素都放到queue中,由于要记住层次,所有需要pair<string,int>
写法2用set实现,set只填充当前层所有的元素,用count记住层次(代码中把set改为unordered_set,速度更快)
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
set<string> wordSet(wordList.begin(),wordList.end());
set<string> cur;
cur.insert(beginWord);
int count = 0;
while(!cur.empty()) {
set<string> t;
for(auto s:cur) {
if(s == endWord) return count+1;
for(int j = 0 ; j < s.size(); j++) {
string temp = s;
for(int z = 0 ; z < 26; z++) {
temp[j] = 'a' + z;
if(wordSet.find(temp) != wordSet.end()) {
t.insert(temp);
wordSet.erase(temp);
}
}
}
}
cur = t;
count++;
}
return 0;
}
};