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 intermediate word must exist in the word list
For example,
Given:
beginWord =
endWord =
wordList =
beginWord =
"hit"
endWord =
"cog"
wordList =
["hot","dot","dog","lot","log"]
As one shortest transformation is
return its length
"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:
Using BFS and start at two ends in the same time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int helper(queue<string>& sWord, queue<string>& eWord, int sHubs, int eHubs, | |
unordered_map<string, bool>& wordList, | |
unordered_map<string, bool>& sMap, unordered_map<string, bool>& eMap){ | |
int s=sWord.size(); | |
bool sFindNewWord=false; | |
for(int i=0; i<s; i++){ | |
string w=sWord.front(); | |
sWord.pop(); | |
if(eMap[w]==true) | |
return sHubs+eHubs; | |
for(int j=0; j<w.length(); j++) | |
for(int k=0; k<26; k++){ | |
string tmp=w; | |
tmp[j]='a'+k; | |
if(sMap[tmp]!=true&&wordList[tmp]==true){ | |
sWord.push(tmp); | |
sMap[tmp]=true; | |
sFindNewWord=true; | |
} | |
} | |
} | |
sHubs=sFindNewWord? sHubs+1:sHubs; | |
int e=eWord.size(); | |
bool eFindNewWord=false; | |
for(int i=0; i<e; i++){ | |
string w=eWord.front(); | |
eWord.pop(); | |
if(sMap[w]==true) | |
return sHubs+eHubs; | |
for(int j=0; j<w.length(); j++) | |
for(int k=0; k<26; k++){ | |
string tmp=w; | |
tmp[j]='a'+k; | |
if(eMap[tmp]!=true&&wordList[tmp]==true){ | |
eWord.push(tmp); | |
eMap[tmp]=true; | |
eFindNewWord=true; | |
} | |
} | |
} | |
eHubs=eFindNewWord? eHubs+1:eHubs; | |
if(!sFindNewWord&&!eFindNewWord) | |
return 0; | |
else | |
return helper(sWord, eWord, sHubs, eHubs, wordList, sMap, eMap); | |
} | |
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { | |
unordered_map<string, bool> myMap; | |
for(auto it =wordList.begin(); it!=wordList.end(); it++) | |
myMap[*it]=true; | |
queue<string> sWord; | |
queue<string> eWord; | |
unordered_map<string, bool> sMap; | |
unordered_map<string, bool> eMap; | |
sWord.push(beginWord); | |
eWord.push(endWord); | |
sMap[beginWord]=true; | |
eMap[endWord]=true; | |
int sHubs=1; | |
int eHubs=1; | |
return helper(sWord, eWord, sHubs, eHubs, myMap, sMap, eMap); | |
} | |
}; |
No comments:
Post a Comment