BFS中队列大小的重要性

Importance of the size of the queue in BFS

本文关键字:重要性 队列 BFS      更新时间:2023-10-16

我正在尝试在leetcode上解决以下问题:https://leetcode.com/problems/word-ladder/description/。问题是:

给定两个单词(beginWordendWord(和一个字典 wordList,我们必须找到最短转换的长度 从 beginWordendWord的序列使每个中间体 字典中的单词在每个步骤中,我们只能更改一个 信。因此,如果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++;
        }
    }