繁体   English   中英

深度优先搜索

[英]Depth-first search

我有一个后缀树,该树的每个节点都是一个结构

struct state {
int len, link;
map<char,int> next; };
state[100000] st;

我需要为每个节点制作dfs并获取所有可以到达的字符串,但是我不知道该如何制作。 这是我的DFS功能

 void getNext(int node){
  for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
      getNext(it->second);
 }
}

如果我可以做这样的事情将是完美的

map<int,vector<string> >

int是我的树和向量字符串的节点,可以到达

现在可以了

void createSuffices(int node){//, map<int, vector<string> > &suffices) {
if (suffices[sz - 1].size() == 0 && (node == sz - 1)) {
    // node is a leaf
    // add a vector for this node containing just 
    // one element: the empty string
    //suffices[node] = new vector<string>
    //suffices.add(node, new vector<string>({""}));
    vector<string> r;
    r.push_back(string());
    suffices[node] = r;
} else {
    // node is not a leaf
    // create the vector that will be built up
    vector<string> v;
    // loop over each child
    for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
        createSuffices(it->second);
        vector<string> t = suffices[it->second];
        for(int i = 0; i < t.size(); i ++){
            v.push_back(string(1,it->first) + t[i]);
        }
    }
    suffices[node] = v;
}
}

您可以将map<int, vector<string>>连同深度优先搜索一起传递。 当从某个节点n返回递归调用时,您知道该节点的所有条件都已准备就绪。 我的C ++技能太有限,因此我将用伪代码编写它:

void createSuffices(int node, map<int, vector<string>> suffices) {
    if (st[node].next.empty()) {
        // node is a leaf
        // add a vector for this node containing just 
        // one element: the empty string
        suffices.add(node, new vector<string>({""}));
    } else {
        // node is not a leaf
        // create the vector that will be built up
        vector<string> v;
        // loop over each child
        foreach pair<char, int> p in st[node].next {
            // handle the child
            createSuffices(p.second, suffices);

            // prepend the character to all suffices of the child
            foreach string suffix in suffices(p.second) {
                v.add(concatenate(p.first, suffix));
            }                
        }
        // add the created vector to the suffix map
        suffices.add(node, v);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM