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.
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.
最短路径问题,用BFS解决
class Solution {
public:
bool diff_one(string org,string s){
bool ret = false;
for(int i = 0; i< org.length(); i++){
if(org[i] != s[i]){
if(ret)
return false;
else
ret = true;
}
}
return ret;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length() || wordList.size() == 0)
return 0;
int ans = 0,cur = 1,next = 0;
bool found = false;
queue<string> q;
string s;
q.push(beginWord);
while(!q.empty()){
s = q.front();
if(s == endWord){
found = true;
break;
}
vector<string>::iterator itr = wordList.begin();
while(itr != wordList.end()){
if(diff_one(s, *itr)){
q.push(*itr);
wordList.erase(itr);
next ++;
continue;
}
itr ++;
}
q.pop();
if(--cur == 0){
cur = next;
next = 0;
ans ++;
}
}
return found ? ++ans : 0;
}
};
本文介绍了一种使用广度优先搜索(BFS)算法来解决单词转换问题的方法,目标是从一个开始单词通过字典中的一系列单词转换到目标单词,每次只改变一个字母,并确保所有中间单词都在给定的字典中。

490

被折叠的 条评论
为什么被折叠?



