Leetcode 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:
- Only one letter can be changed at a time.
- 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.
1 public class Solution { 2 public class QueueNode 3 { 4 public string val; 5 public int step; 6 7 public QueueNode(string v, int s) 8 { 9 val = v; 10 step = s; 11 } 12 } 13 14 public int LadderLength(string beginWord, string endWord, IList<string> wordList) { 15 var hashset = new HashSet<string>(); 16 17 foreach (var s in wordList) 18 { 19 hashset.Add(s); 20 } 21 22 if (!hashset.Contains(endWord)) return 0; 23 24 var queue = new Queue<QueueNode>(); 25 queue.Enqueue(new QueueNode(beginWord, 1)); 26 int len = beginWord.Length; 27 28 while (queue.Count > 0) 29 { 30 var q = queue.Dequeue(); 31 32 for (int j = 0; j < len; j++) 33 { 34 for (int k = 0; k < 26; k++) 35 { 36 var sb = new StringBuilder(q.val); 37 sb[j] = (char)((int)'a' + k); 38 39 var ns = sb.ToString(); 40 if (ns == endWord) 41 { 42 return q.step + 1; 43 } 44 else if (hashset.Contains(ns)) 45 { 46 queue.Enqueue(new QueueNode(ns, q.step + 1)); 47 hashset.Remove(ns); 48 } 49 } 50 } 51 52 } 53 54 return 0; 55 } 56 }

浙公网安备 33010602011771号