// bfs + 剪枝
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
// 1.将所有的单词放在set字段中
unordered_set<string> s;
for (auto & ele : wordList) s.insert(ele);
// 单词 + 步数
queue<pair<string,int> > que;
que.push({beginWord,1});
s.erase(biginWord);// 避免再次找到次字符串,避免找回来
int step = 0;
string temp = "";
while (!que.empty()) {
if (que.front().first == endWord) {
return que.front().second;
}
temp = que.front().first;
step = que.front().second;
que.pop();
// bfs下一个结点,就是将beginWord挨个替换
char ch;
for (int i = 0; i < temp.size(); ++ i) {
ch = temp[i];
for (char j = 'a'; j <= 'z'; ++ j ) {
if (j == ch) continue; // 已存在的不进行寻找
temp[i] = j;
// 如果在字典中
if (s.find(temp) != s.end()) {
que.push({temp,step + 1});
// 同时让其字典伤处这个元素,避免查找回来
s.erase(temp);
}
}
// 复原 = 回溯
temp[i] = ch;
}
}
return 0;
}
};
leetCode127. 单词接龙
于 2024-06-10 20:47:21 首次发布