127. Word Ladder

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

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.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

———————————————————————————————————————————————————-

Basically this question asks search algorithm by BFS (breath first search). I have tried to use recursive function but not working in the big sample. Of course, the complexity is exponentially grown, just failed to do it.

Furthermore, only two way BFS is working. One way will stop in case of 6 or 7 steps. So logic must start with beginword part and endword part at the same time.

public class Solution
{
  public int LadderLength(string beginWord, string endWord, IList<string> wordList)
  {
    int minDepth = 0;
    
    HashSet<string> dictionary = new HashSet<string>();
    wordList.ToList().ForEach(a => dictionary.Add(a));
    
    HashSet<string> beginSet = new HashSet<string>();
    HashSet<string> endSet = new HashSet<string>();
    beginSet.Add(beginWord);
    endSet.Add(endWord);
    
    bool toggle = true;
    
    while(true)
    {
      minDepth++;

      var checkQuery =
        from a in beginSet
        from b in endSet
        where a == b
        select a;
      
      // if found
      if(checkQuery.Any())
        return minDepth;

      HashSet<string> tempBeginSet = new HashSet<string>();
      HashSet<string> tempEndSet = new HashSet<string>();
      
      if(toggle)
      {
        // update begin Set
        for (int i = 0; i < beginSet.Count; i++)
        {
          string query = beginSet.ElementAt(i);
          List<string> tempResult = GetAllThings(query, dictionary, beginWord);
          tempResult.ForEach(a => tempBeginSet.Add(a));
        }
        beginSet = tempBeginSet;
        toggle = !toggle;
      } else
      {
        for (int i = 0; i < endSet.Count; i++)
        {
          string query = endSet.ElementAt(i);
          List<string> tempResult = GetAllThings(query, dictionary, beginWord);
          tempResult.ForEach(a => tempEndSet.Add(a));
        }
        endSet = tempEndSet;
        toggle = !toggle;
      }
      
      // exit count
      if(minDepth > dictionary.Count)
        return 0;
    }
    
    return 0;
  }
  
  public List<string> GetAllThings(string str, HashSet<string> dictionary, string beginWord)
  {
    List<string> result = new List<string>();

    if (str != beginWord && !dictionary.Contains(str))
      return result;

    char[] arr = str.ToCharArray();
    for (int i = 0; i < arr.Length; i++)
    {
      char c = arr[i];
      for (int j = 'a'; j <= 'z'; j++)
      {
        if(c == ((char)j))
          continue;
        
        string temp = str.Remove(i,1).Insert(i, ((char)j)+"");
        
        if(dictionary.Contains(temp))
          result.Add(temp);
      }
    }
    return result;
  }

}
  

Leave a comment