BFS中队列大小的重要性
Importance of the size of the queue in BFS
我正在尝试在leetcode上解决以下问题:https://leetcode.com/problems/word-ladder/description/。问题是:
给定两个单词(
beginWord
和endWord
(和一个字典wordList
,我们必须找到最短转换的长度 从beginWord
到endWord
的序列使每个中间体 字典中的单词在每个步骤中,我们只能更改一个 信。因此,如果beginword ='hit''而端字是'cog',并且dict具有["hot","dot","dog","lot","log","cog"]
,然后答案是5
。
我试图理解高度投资的解决方案(比我的更好(,如下所示:
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
wordDict.insert(endWord);
queue<string> toVisit;
addNextWords(beginWord, wordDict, toVisit);
int dist = 2;
while (!toVisit.empty()) {
int num = toVisit.size();
for (int i = 0; i < num; i++) { //-->why this for loop?
string word = toVisit.front();
toVisit.pop();
if (word == endWord) return dist;
addNextWords(word, wordDict, toVisit);
}
dist++;
}
}
private:
void addNextWords(string word, unordered_set<string>& wordDict, queue<string>& toVisit) {
wordDict.erase(word);
for (int p = 0; p < (int)word.length(); p++) {
char letter = word[p];
for (int k = 0; k < 26; k++) {
word[p] = 'a' + k;
if (wordDict.find(word) != wordDict.end()) {
toVisit.push(word);
wordDict.erase(word);
}
}
word[p] = letter;
}
}
};
我理解几乎整个解决方案,我不了解迭代toVisit.size()
次的直觉。这也不是标准BFS算法的一部分。有人可以指出这个循环背后的直觉 - 它到底是做什么,为什么范围(比队列的大小小0到1(?
存在循环,以确保我们只有在访问了与开始时的所有单词后才递增。另一个用户酶
循环内部循环的原因从队列的0到大小是随着搜索的开发:
- 新单词添加到您要迭代的队列中,
- 同时,将当前单词从该队列中删除。
此循环将迭代限制为最初在队列中的单词,并确保对队列进行的修改不会影响搜索的当前阶段。
如果您盯着它更长一点,您将看到发生了什么。
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
wordDict.insert(endWord);
queue<string> toVisit;
addNextWords(beginWord, wordDict, toVisit);
int dist = 2;
while (!toVisit.empty()) {
int num = toVisit.size();
for (int i = 0; i < num; i++) {
string word = toVisit.front();
toVisit.pop(); // <-- remove from front of queue
if (word == endWord) return dist;
addNextWords(word, wordDict, toVisit); // <-- add to back of queue
}
dist++;
}
}
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 打印优先级队列
- 共享队列的线程安全
- 带自定义比较器的最小优先级队列
- 在 Vulkan Qt 中获取队列系列
- 堆栈和队列是否像C++中的数组一样传递?
- 在C++中创建队列 - 什么是 malloc 错误?
- BFS中队列大小的重要性