zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    内聚和耦合的举例
    OneZero第四周第五次站立会议(2016.4.15)
    OneZero第四周第四次站立会议(2016.4.14)
    OneZero团队Beta发布剧透
    PSP(4.6——4.12)以及周记录
    关于“内聚和耦合”
    CSV 注入实战
    BurpSuite 一些小技巧
    博客园URL跳转钓鱼
    【Demo 0005】Android 资源
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5873913.html
Copyright © 2011-2022 走看看