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
1 class Solution { 2 public: 3 int ladderLength(string start, string end, unordered_set<string> &dict) { 4 if(match(start,end)) 5 return 2; 6 queue<string> q; 7 map<string,int> m; 8 q.push(start); 9 m[start]=1; 10 while(!q.empty()){ 11 string tmp=q.front(); 12 q.pop(); 13 for(int i=0;i<tmp.length();i++){ 14 for(char c='a';c<='z';c++){ 15 if(c==tmp[i]) 16 continue; 17 string next=tmp; 18 next[i]=c; 19 if(next==end){ 20 return m[tmp]+1; 21 } 22 if(dict.find(next)!=dict.end()&&m.find(next)==m.end()){ 23 q.push(next); 24 m[next]=m[tmp]+1; 25 } 26 } 27 } 28 } 29 return 0; 30 } 31 bool match(string src,string dst){ 32 if(src.length()!=dst.length()){ 33 return false; 34 } 35 int count=0; 36 for(int i=0;i<src.length();i++){ 37 if(src[i]!=dst[i]) 38 count++; 39 } 40 return count==1?true:false; 41 } 42 };