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.
初次接触这样题目的人,会看不懂题目的意图。其实这个跳跃,可以看成一幅图,只有一个字母不同的两个单词之间有连线,其他没有。这样,最小的跳跃长度,就是图的最短路径。
由于这幅图之间每个节点的距离相等,所以使用广度优先搜索就可以找到最短路径。
1. 由于是图的搜索,所以需要标记节点是否访问过的方法,我就用set来实现,如果set中包含某个单词,那么这个单词就没有被访问过。
否则,把这个单词加入到vist集合当中。
2. 对于单词之间的距离,由于字母总共有26个,所以可以用暴力的方法来求距离相聚为一的两个单词。
3.在搜索时,每向外圈多扩展一圈,就把步数加一。最后遇到目的单词,搜索结束。
class Solution
{
public:
int ladderLength(string start,string end,unordered_set<string> &dict)
{
set<string> visit;
int count = 1,len = 0,i=0,j=0,k=0;
int len2 = start.size();
queue<string> que;
if(start.compare(end)==0)
{
return 1;
}
que.push(start);
visit.insert(start);
while(que.size()>0)
{
len = que.size();
//cout<<que.size()<<endl;
for(i=0;i<len;i++)
{
string tmp = que.front();
que.pop();
for(j=0;j<len2;j++)
{
char tc = tmp[j];
for(k='a';k<'z';k++)
{
tmp[j] = k;
// remember the dictionary
if(dict.count(tmp)!=0)
{
if(visit.count(tmp)==0)
{
if(tmp.compare(end)==0)
{
//cout<<tmp<<endl;
return count+1;
}
visit.insert(tmp);
que.push(tmp);
}
}
}
tmp[j] = tc;
}
}
count++;
}
return 0;
}
};