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:

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

c++

int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList)
{
int len = 1, slen = beginWord.length(),n;
queue<string> q;
q.push(beginWord);
while ((n = q.size()) > 0)
{
len++;
for (int i = 0; i < n; i++)
{
string s = q.front();
q.pop();
for (int j = 0; j < slen; j++)
{
char ch = s[j];
for (char c = 'a'; c <= 'z'; c++)
{
s[j] = c;
if (s == endWord)
return len;
if (wordList.find(s) != wordList.end())
{
q.push(s);
wordList.erase(s);
}
s[j] = ch;
}
}
}
}
return 0;
}

public int LadderLength(string beginWord, string endWord, ISet<string> wordList)
{
int len = 1,slen= beginWord.Length,n;
Queue<string> q = new Queue<string>();
q.Enqueue(beginWord);
while ((n=q.Count)>0)
{
len++;
for (int i = 0; i < n; i++)
{
string s = q.Dequeue();
for (int j = 0; j < slen; j++)
{
char[] ch = s.ToCharArray();
for (char c = 'a'; c <= 'z'; c++)
{
ch[j] = c;
string tmp = new string(ch);
if (tmp == endWord)
return len;
if (wordList.Contains(tmp))
{
q.Enqueue(tmp);
wordList.Remove(tmp);
}
}
}
}
}
return 0;
}

• 本文已收录于以下专栏：

## [Leetcode 126 & 127, hard & medium] Word Ladder II & I

[Leetcode 126 & 127, hard & medium] Word Ladder II & I

Given two words (start and end), and a dictionary, find the length of shortest transformation sequen...

## LeetCode 127 Word Ladder (广度优先搜索)

class Solution { public: int ladderLength(string beginWord, string endWord, vector& wordList) { u...

Given two words (start and end), and a dictionary, find the length of shortest transformation sequen...