簡體   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