基于C++的BooStruWork实现

基于C++的BooStruWork实现,c++,C++,在上面的函数中,尝试首先检查列表中的每个元素,如果它不是搜索的节点,则对其进行标记,然后对每个标记的点反复调用函数,如果找到它,则返回节点名。 我遇到的问题,没有进入深度搜索,因为如果我做它递归它将始终首先检查它的深度,然后再做下一步。。。 此外,如果路径被找到,我在保护路径安全和返回路径方面遇到问题 我希望您理解我的意思,抱歉我的英语不好上描述的广度优先搜索算法不需要递归性。伪代码讨论用于排序的队列q和集合V大写V,以确保重复值只匹配一次,我在下面的代码中省略了这一点: 0 -> 1 1

在上面的函数中,尝试首先检查列表中的每个元素,如果它不是搜索的节点,则对其进行标记,然后对每个标记的点反复调用函数,如果找到它,则返回节点名。 我遇到的问题,没有进入深度搜索,因为如果我做它递归它将始终首先检查它的深度,然后再做下一步。。。 此外,如果路径被找到,我在保护路径安全和返回路径方面遇到问题

我希望您理解我的意思,抱歉我的英语不好

上描述的广度优先搜索算法不需要递归性。伪代码讨论用于排序的队列q和集合V大写V,以确保重复值只匹配一次,我在下面的代码中省略了这一点:

0 -> 1
1 -> 0 -> 2
2 -> 1

也许有人可以给我看一个在c++11中使用列表的工作新娘搜索示例,你是说?是的,sry,你是对的
0 -> 1
1 -> 0 -> 2
2 -> 1
#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;

template<class T>
struct tree_item {
    T value;
    vector<tree_item<T>> children;

    tree_item(T value) : value(value) {}
};

// constructs animated gif http://en.wikipedia.org/wiki/Breadth-first_search
tree_item<string> build_tree() {
    tree_item<string> a("a"), b("b"), c("c"), d("d"), e("e"), f("f"), g("g"), h("h");

    e.children = { h };
    b.children = {d, e};
    c.children = {f, g};
    a.children = {b, c};

    return a;
}

// implements "Algorithm" -> "Pseudocode" http://en.wikipedia.org/wiki/Breadth-first_search
template<class T>
bool find_breadth_first(const tree_item<T>& v, function<bool(const T&)> matcher, tree_item<T>& found_item) {
    queue<const tree_item<T>*> q; // step 2
    q.push(&v); // step 5

    while(!q.empty()) { // step 6
        auto t = q.front(); q.pop(); // step 7

        cout << "currently visiting " << t->value << endl;
        if(matcher(t->value)) { // step 8
            cout << t->value << " is a match " << endl;
            found_item = *t; return true; // step 9
        }

        for(auto& u : t->children) // step 11
            q.push(&u); // step 15
    }

    return false; // step 19
}

int main() {
    auto root = build_tree();

    tree_item<string> match("no match");
    auto matcher = [&](auto candidate) {
        return candidate == "g";
    };

    auto found = find_breadth_first<string>(root, matcher, match);

    if(found)
        cout << "found: " << match.value << endl;
    else
        cout << "not found" << endl;
}
currently visiting a
currently visiting b
currently visiting c
currently visiting d
currently visiting e
currently visiting f
currently visiting g
g is a match 
found: g