Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation
sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["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.
Solution: BFS.
1 class Solution { 2 public: 3 int ladderLength(string start, string end, unordered_set<string> &dict) { 4 queue<pair<string, int>> q; // (word, transformation steps) 5 q.push(make_pair(start, 1)); 6 while (!q.empty()) 7 { 8 pair<string, int> front = q.front(); 9 q.pop(); 10 string word = front.first; // first word must be included in dictionary 11 for (size_t i = 0; i < word.size(); i++) 12 { 13 char before = word[i]; 14 for (char c = 'a'; c <= 'z'; c++) 15 { 16 word[i] = c; 17 if (word == end) 18 return front.second + 1; 19 if (dict.find(word) != dict.end()) 20 { 21 q.push(make_pair(word, front.second + 1)); 22 dict.erase(word); 23 } 24 } 25 word[i] = before; 26 } 27 } 28 return 0; 29 } 30 };