您的位置:首页 > 编程语言 > C语言/C++

leetcode #127 in cpp

2016-06-20 12:32 429 查看
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord toendWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list

For example,

Given:
beginWord = 
"hit"

endWord = 
"cog"

wordList = 
["hot","dot","dog","lot","log"]


As one shortest transformation is 
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
,

return its length 
5
.

Solution:

Since we are to get shortest length, we should perform BFS. In BFS, we scan through current words in queue. For each word, we change one letter and see if new word in in the dictionary. If so we put the new word in queue.  By this we reach the endWord with
fewest levels. This gives us the shortest length of change from beginword to e

Code:

class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
if(beginWord == endWord) {

return 0;
}

deque<string> next;//BFS traversal
next.push_back(beginWord);
if(wordList.find(beginWord)!=wordList.end()) wordList.erase(beginWord);

int step = 0;

bool isfound = false;
while(!next.empty()){
int cap = next.size();
<span style="white-space:pre"> </span>//for current level, collect the next level
while(cap>0){
string word = next.front();
next.pop_front();
if(word == endWord){//if we meet endword, we terminate.
return step+1;
}else{
<span style="white-space:pre"> </span>//change one letter only
for(int j = 0; j < word.length(); j ++){
char c = word[j];
for(int i = 'a'; i <='z'; i++){
if(c == i) continue;
word[j] = i;
<span style="white-space:pre"> </span> //after changing one letter, if the new word in in the dictionary, push it into queue
if(wordList.find(word)!=wordList.end()){
next.push_back(word);
}
}
word[j] = c;
}
}
cap--;
}
<span style="white-space:pre"> </span>//erase the word we have met in the dictionary. This prevents going back and forth like hot -> dot->hot->dot.
for(int i = 0; i < next.size(); i ++){
wordList.erase(next[i]);
}
if(isfound) break;
step ++;
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode