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 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.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
开始我的想法是用回溯法列出所有可能,再从里面挑选出路径最小的,这样做穷举的数量太大,最后time limited
错误代码示范:
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList)
{
vector<string>temp;
vector<int>count;
temp.push_back(beginWord);
helper(endWord,wordList,temp,count);
if(count.size()==0)
return 0;
int min=count[0];
for(int i=0;i<count.size();i++)
if(count[i]<min)
min=count[i];
return min;
}
void helper(string endWord, unordered_set<string>& wordList,vector<string>&temp,vector<int> &count)
{
if(check(endWord,temp[temp.size()-1]))
{
count.push_back(temp.size()+1);
//for(int i=0;i<temp.size();i++)
// cout<<temp[i]<<' ';
// cout<<endl<<endl;
}
for(auto it=wordList.begin();it!=wordList.end();it++)
{
if(find(temp.begin(),temp.end(),*it)!=temp.end())
continue;
if(check(*it,temp[temp.size()-1]))
{
temp.push_back(*it);
helper(endWord,wordList,temp,count);
temp.pop_back();
}
}
}
bool check(string a,string b)
{
int count=0;
for(int i=0;i<a.size();i++)
{
if(a[i]!=b[i])
count++;
}
if(count==1)
return true;
return false;
}
};
我从网上看到了一篇帖子,分析的很好,用的方法是求路径的BFS
代码如下:
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList)
{
int n=beginWord.size();
if(0==n)
return 0;
int distance=1;
queue<string>quetopush;
queue<string>quetopop;
quetopop.push(beginWord);
while(wordList.size()>0&&!quetopop.empty())
{
while(!quetopop.empty())
{
string str=quetopop.front();
quetopop.pop();
for(int i=0;i<str.size();i++)
{
for(char j='a';j<='z';j++)
{
if(j==str[i])
continue;
char temp=str[i];
str[i]=j;
if(str==endWord)
return distance+1;
if(wordList.count(str))
{
quetopush.push(str);
wordList.erase(str);
}
str[i]=temp;
}
}
}
distance++;
swap(quetopush,quetopop);
}
return 0;
}
};