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,也可以用queue<pair<string,int>> q;
struct Node{ string word; int len;//到达这个字符串所走的长度 Node(string w,int l):word(w),len(l){} }; class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> wordDict(wordList.begin(),wordList.end()); 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; //查找邻居 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; if(wordDict.find(frontwordcp)!=wordDict.end()&&frontwordcp==endWord) { return frontnode->len+1; } if(wordDict.find(frontwordcp)!=wordDict.end()&&m[frontwordcp]==false) { int lentmp=frontnode->len+1; //printf("lentmp=%d\n",lentmp); Node* neighborNode=new Node(frontwordcp,lentmp); //printf("neighborNode len=%d") //printf("frontnode->len=%d frontwordcp=%s neighborNode->len=%d\n",frontnode->len,neighborNode->word.c_str(),neighborNode->len); q.push(neighborNode); m[frontwordcp]=true; } } } } return 0; } };
class Solution { public: int ladderLength(string start, string end, vector<string>& wordList) { unordered_set<string> dict(wordList.begin(),wordList.end()); return BFS(start,end,dict); } private: int BFS(string start,string end,unordered_set<string> &dict){ // 存放单词和单词所在层次 queue<pair<string,int> > q; q.push(make_pair(start,1)); unordered_set<string> visited; visited.insert(start); // 广搜 bool found = false; while(!q.empty()){ pair<string,int> cur = q.front(); q.pop(); string word = cur.first; int len = word.size(); // 变换一位字符 for(int i = 0;i < len;++i){ string newWord(word); for(int j = 0;j < 26;++j){ newWord[i] = 'a' + j; if(dict.count(newWord) > 0&&newWord == end){ found = true; return cur.second+1; }//if // 判断是否在字典中并且是否已经访问过 if(dict.count(newWord) > 0 && visited.count(newWord) == 0){ visited.insert(newWord); q.push(make_pair(newWord,cur.second+1)); }//if }//for }//for }//while if(!found){ return 0; }//if } };