这道题目需要用BFS求单源最短路径和
这个算法会超时
class Solution {
public:
bool check(string a, string b)
{
int res = 0;
for (int i = 0; i < a.size(); i ++ ) res += a[i] != b[i];
return res == 1;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
bool flag = false;
for(auto word:wordList){
if(word==endWord) flag = true;
}
if(!flag) return false;
unordered_map<string, int> dist;
queue<string> q;
q.push(beginWord), dist[beginWord] = 1;
while (!q.empty())
{
string tmp = q.front();
q.pop();
if (tmp == endWord) return dist[tmp];
for(auto word:wordList){
if(check(tmp,word)&&dist[word]==0){
dist[word] = dist[tmp] + 1;
q.push(word);
}
}
}
return 0;
}
};
要在这个基础上做一个优化
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
bool flag = false;
unordered_set<string> wordSet;
for(auto word:wordList){
wordSet.insert(word);
}
if(!wordSet.count(endWord)) return false;
unordered_map<string, int> dist;
queue<string> q;
q.push(beginWord), dist[beginWord] = 1;
while (!q.empty())
{
string tmp = q.front();
q.pop();
if (tmp == endWord) return dist[tmp];
for(int i=0;i<tmp.size();i++){
for(char c='a';c<='z';c++){
string old = tmp;
tmp[i] = c;
if(wordSet.count(tmp)&&dist[tmp]==0){
q.push(tmp);
dist[tmp] = dist[old]+1;
}
tmp = old;
}
}
}
return 0;
}
};