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;
        }
  • 相关阅读:
    那些陌生的C++关键字
    从实现装饰者模式中思考C++指针和引用的选择
    单例模式(Singleton)
    命令模式(Command)
    抽象工厂模式(Abstract Factory)
    《Effective C++》读书摘要
    桥接模式(Bridge)
    适配器模式(Adapter)
    设计模式学习心得
    黑客常用WinAPI函数整理
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5873913.html
Copyright © 2011-2022 走看看