Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["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.
pro:一个start string,一个end string,一个dict,求将start变到end所需要的最小的步数,要求是每一步变换一个字符,中间结果都在dict中。
sol:
就是一个bfs,遍历每一位替换为其他字符所变换得到的单词,进队的条件是这个单词没被放进去过,这里用unordered_set,用map竟然tle......,以及单词在dict中。
code:
class Solution
{
public:
int ladderLength(string start,string end,unordered_set<string> &dict)
{
int i,j,k,step;
char ch;
string temp,front;
unordered_set<string> myset;
myset.clear();
queue< pair<string,int> > myque;
while(!myque.empty())
myque.pop();
myque.push(make_pair(start,1));
myset.insert(start);
while(!myque.empty())
{
front = myque.front().first;
step = myque.front().second;
myque.pop();
if(front==end)
return step;
for(i=0;i<front.length();i++)
{
temp=front;
for(j=0;j<26;j++)
{
char ch=j+'a';
if(ch!=front[i])
{
temp[i]=ch;
if(temp==end) return step+1;
if(myset.find(temp)==myset.end()&&dict.find(temp)!=dict.end())
{
myset.insert(temp);
myque.push(make_pair(temp,step+1));
}
}
}
}
}
return 0;
}
};