bfs的经典题目:代码:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int minLength = INT_MAX;
// 构造图的邻接举证表示
unordered_map<string, vector<string>> stringMap;
for(const auto &s : wordList) {
if(canConvert(beginWord, s))
stringMap[beginWord].push_back(s);
}
for(const auto &s1 : wordList) {
for(const auto &s2 : wordList) {
if(canConvert(s1, s2))
stringMap[s1].push_back(s2);
}
}
/* 广度优先搜索 */
queue<int> q1;
queue<string> q2;
unordered_set<string> hashmap;
q1.push(1);
q2.push(beginWord);
hashmap.insert(beginWord);
while(q1.size()) {
int len = q1.front();
string word = q2.front();
q1.pop();
q2.pop();
if(word == endWord) {
if(minLength > len)
minLength = len;
}
const vector<string> &wordlist = stringMap[word];
for(const auto &w : wordlist) {
if(hashmap.end() == hashmap.find(w)) {
q1.push(len + 1);
q2.push(w);
hashmap.insert(w);
}
}
}
return minLength == INT_MAX ? 0 : minLength;
}
private:
/* 假定A和B不为空且长度相等 */
bool canConvert(const string &A, const string &B) {
int count = 0;
for(int i = 0; i < A.length(); i++) {
if(A[i] != B[i])
count++;
}
return (count <= 1);
}
};