- 描述
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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
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.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
- 思路
这道题可以使用广度优先遍历的思想去求解。初始化一个队列Q,这个队列Q用于存放跟startWord相差一个字母的字符。在开始时将startWord添加到这个队列中,然后不停的循环该队列,每次将集合中与出队列的字符串相差1的字符串添加到该队列中,直到该队列出的字符串等于endWord。需要注意,集合中的元素只能进队列一次,否则将造成无限循环的可能。代码见下 - 代码(c#)
public int LadderLength(string beginWord, string endWord, IList<string> wordList)
{
Queue<Word> queue = new Queue<Word>();
queue.Enqueue(new Word() { Count = 1, BeginWord = beginWord });
bool[] isVisit = new bool[wordList.Count];//保存该字符串是否已进入队列
while (queue.Count > 0)
{
Word word = queue.Dequeue();
if (word.BeginWord == endWord) return word.Count;//得到最短的转化路径
for (int i = 0; i < wordList.Count; i++)
{
if (isVisit[i])
{
continue;
}
if (Vaild(word.BeginWord, wordList[i]))//判断该wordList[i]字符是否与BeginWord相差1个字母
{
queue.Enqueue(new Word() { Count = word.Count + 1, BeginWord = wordList[i] });
isVisit[i] = true;
}
}
}
return 0;
}
public class Word
{
public int Count { get; set; }
public string BeginWord { get; set; }
}
public bool Vaild(string s1, string s2)
{
bool flag = false;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] != s2[i])
{
if (!flag) flag = true;
else
{
return false;
}
}
}
return flag;
}
- 总结
在求解时一定要将所有的情况考虑清楚,排除可能会出现重复的情况。博主因为没有排除重复的情况而debug了很久。 - 相关链接
LeetCode原题:https://leetcode.com/problems/word-ladder/description/
参考博客:http://blog.csdn.net/liuchuo/article/details/54728297