127. Word Ladder

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord 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.

 

 

public int LadderLength(string beginWord, string endWord, ISet<string> wordList) {
        var beginSet = new HashSet<string>();
        var endSet = new HashSet<string>();
        var visited = new HashSet<string>();
        
        beginSet.Add(beginWord);
        endSet.Add(endWord);
        int res=1;
        while(beginSet.Count() >0 && endSet.Count() > 0)
        {
            if(beginSet.Count() > endSet.Count())
            {
                var temp1 = beginSet;
                beginSet = endSet;
                endSet = temp1;
            }
            
            var temp = new HashSet<string>();
            foreach( string word in beginSet)
            {
                var c = word.ToCharArray();
                for(int i = 0;i<c.Length;i++)
                {
                    var old = c[i];//keep the old value and unchange the string after the subloop
                    for(char j = 'a';j<='z';j++)
                    {
                        c[i] = j;
                        string dest = new string(c);
                        if(endSet.Contains(dest)) return res+1;
                        if(!visited.Contains(dest)&& wordList.Contains(dest))
                        {
                            temp.Add(dest);
                            visited.Add(dest);
                        }
                      
                    }
                    c[i] = old;
                }
            }
            
            beginSet = temp;
            res++;
        }
        return 0;
    }

 

posted @ 2016-09-14 23:03  咖啡中不塌缩的方糖  阅读(169)  评论(0编辑  收藏  举报