20+ lines Easy to understand C# code ~700ms


  • 0
    public int LadderLength(string beginWord, string endWord, IList<string> wordList) {            
                int height = 0;            
                var wordls = new List<string>(wordList);
                var wqueue = new Queue<string>();
                wqueue.Enqueue(beginWord);            
                while (wqueue.Count != 0)
                {
                    var cvisitedList = new HashSet<string>();
                    height++;
                    while (wqueue.Count != 0)
                    {
                        var word = wqueue.Dequeue();
                        foreach (var item in wordls.Where(x => isLadderWord(word, x)))
                        {
                            cvisitedList.Add(item);
                            if (item.Equals(endWord))                        
                                return height + 1;                        
                        }
                    }
                    wordls.RemoveAll(x => cvisitedList.Contains(x));
                    cvisitedList.ToList().ForEach(x => wqueue.Enqueue(x));
                }
                return 0;
        }
        public static bool isLadderWord(string s1, string s2)
            {
                int diffcount = 0;            
                for (int i = 0; i < s1.Length; i++)
                {
                    if (s1[i] != s2[i])
                        diffcount++;
                    if (diffcount > 1)
                        break;
                }
                return diffcount == 1;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.