【21】127. Word Ladder
127. Word Ladder
- Total Accepted: 109845
- Total Submissions: 571018
- Difficulty: Medium
- Contributors: Admin
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.
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.
DFS寻找所有路径,BFS最短路径。
1 class Solution { 2 public: 3 int ladderLength(string beginWord, string endWord, vector<string>& wordList) { 4 if(beginWord == endWord) return 1; 5 if(beginWord.size() < 1 || beginWord.size() != endWord.size()) return 0; 6 queue<string> q; 7 8 unordered_set<string> dict;//set 9 for (int i = 0; i < wordList.size(); i++) { 10 dict.insert(wordList[i]); 11 } 12 13 14 q.push(beginWord); 15 dict.erase(beginWord); 16 int step = 2; 17 while(!q.empty()){ 18 int size = q.size(); 19 //string tmp = q.front(); 20 //q.pop(); 21 for(int i = 0; i < size; i++){ 22 23 string tmp = q.front();//pop在里层 24 q.pop(); 25 26 for(int j = 0; j < beginWord.size(); j++){ 27 char old = tmp[j]; 28 for(char c = 'a'; c <= 'z'; c++){ 29 if(old == c) continue; 30 tmp[j] = c; 31 32 if(dict.find(tmp) != dict.end()){ 33 if(tmp == endWord){ 34 return step; 35 } 36 q.push(tmp); 37 dict.erase(tmp); 38 } 39 40 } 41 tmp[j] = old; 42 } 43 //step ++; 44 } 45 step ++;//在while的最外层 46 } 47 //return step; 48 return 0;//否则不成立。只有一个可以return合理值的出口 49 } 50 };