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.
最短搜索路径,所以是广度优先搜索(BFS)。
有几个问题需要注意:
1、怎样判断是否为邻居节点?
按照定义,存在一个字母差异的单词为邻居,因此采用逐位替换字母并查找字典的方法寻找邻居。
(逐个比对字典里单词也可以做,但是在这题的情况下,时间复杂度会变高,容易TLE)
2、怎样记录路径长度?
对队列中的每个单词记录路径长度。从start进入队列记作1.
长度为i的字母的邻居,如果没有访问过,则路径长度为i+1
struct Node { string word; int len; Node(string w, int l): word(w), len(l) {} }; class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { queue<Node*> q; unordered_map<string, bool> m; Node* beginNode = new Node(beginWord, 1); q.push(beginNode); m[beginWord] = true; while(!q.empty()) { Node* frontNode = q.front(); q.pop(); string frontWord = frontNode->word; //neighbor search for(int i = 0; i < frontWord.size(); i ++) { for(char c = 'a'; c <= 'z'; c ++) { if(c == frontWord[i]) continue; string frontWordCp = frontWord; frontWordCp[i] = c; //end if(frontWordCp == endWord) return frontNode->len+1; if(wordDict.find(frontWordCp) != wordDict.end() && m[frontWordCp] == false) { Node* neighborNode = new Node(frontWordCp, frontNode->len+1); q.push(neighborNode); m[frontWordCp] = true; } } } } return 0; } };