【leetcode】Word Ladder

时间:2023-12-29 12:40:02

Word Ladder

Total Accepted: 24823 Total Submissions: 135014My Submissions

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. 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.
Hide Tags

Breadth-first Search

利用广度优先搜索,找到元素的深度即可
寻找相差一个字符的字符串时,考虑采用替换字符的方式寻找,遍历dict在dict很长时,会耗时
 int ladderLength(string start, string end, unordered_set<string> &dict) {
int n=start.size();
if(n<||n!=end.size())
{
return ;
}
if(start==end)
{
return ;
} int level=;
queue<string> q;
q.push(start);
//count用来记录每一个深度的元素的个数
int count=;
while()
{
start=q.front();
q.pop();
count--;
for(int i=;i<start.length();i++)
{
string ori=start;
//每次修改一个字符,看是否在字典中能找到
for(char ch='a';ch<='z';ch++)
{
if(start[i]==ch)continue; start[i]=ch;
if(start==end) return level;
//如果能找到,则用queue记录下下一层深度的元素
if(dict.find(start)!=dict.end())
{
dict.erase(start);
q.push(start);
}
start=ori;
}
} //没有下一层深度了,或者dict已经为空
if(q.empty()||dict.empty())
{
break;
} //count为0,说明该level的元素已经被遍历完了
if(count==)
{
level++;
count=q.size();
}
}
return ;
}