My C# solution


  • 0
    S
    public class Solution {
        public int LadderLength(string beginWord, string endWord, IList<string> wordList) 
        {
            
            if (string.IsNullOrEmpty(beginWord) || string.IsNullOrEmpty(endWord) || wordList == null || !wordList.Any())
                return 0;
            var queue = new Queue<string>();
            queue.Enqueue(beginWord);
            var set = new HashSet<string>(wordList);
            set.Add(beginWord);
            var visited = new HashSet<string>();
            visited.Add(beginWord);
            var result = 1;
            while(queue.Count() > 0)
            {
                var q = new Queue<string>();
                result++;
                while(queue.Count>0)
                {
                    var node = queue.Dequeue();
                    var neighbour = GetNeighbours(node, set);
                    
                    foreach(var n in neighbour)
                    {
                        if(!visited.Contains(n))
                        {
                            visited.Add(n);
                            if(n == endWord)
                            {
                                return result;
                            }
                            else
                            {
                                q.Enqueue(n);
                            }
                        }
                    }
                }
                queue = q;
            }
            return 0;
        }
        
        private List<string> GetNeighbours(string word, HashSet<string> set)
        {
            var result = new List<string>();
            for(int i = 0; i<word.Length; i++)
            {
                var tChar = word[i];
                var tWord = word.ToCharArray();
                for(var c = 'a'; c<='z'; c++)
                {
                    if(c!=tChar)
                    {
                        tWord[i] = c;
                        var newWord = new string(tWord);
                        if(set.Contains(newWord))
                        {
                            result.Add(newWord);
                        }
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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