LeetCode 127. Word Ladder

  • 描述
    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;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值