简体   繁体   English

C++ 中的“扩展”深度优先搜索

[英]"Extended" depth-first search in C++

I know how to implement depth-first search algorithm in C++, but I need an "extended version".我知道如何在 C++ 中实现深度优先搜索算法,但我需要一个“扩展版本”。 So, I have a map所以,我有一张地图

map<int, map<int,int> > tree;

that for any vertex it returns a map with adjacent vertices as keys and (important for my program) edge indexes as values.对于任何顶点,它返回一个以相邻顶点作为键和(对我的程序很重要)边缘索引作为值的映射。 The root of the tree is first (1) vertex.树的根是第一个 (1) 顶点。 So, here is my code:所以,这是我的代码:

stack<int> s;
for(const auto &pair : tree[1]) s.push(pair.first);
while(!s.empty()) {
    if(!visited[s.top()]) {    //it's just bool array
        roads[s.top()] = {0}; // ???
        for(const auto &pair : tree[s.top()]) s.push(pair.first);
    }
    s.pop();
}

What I need to do is create a vector of vectors in which, for every vertex, I'll have a complete path (expressed as edge indexes).我需要做的是创建一个向量向量,其中对于每个顶点,我都有一个完整的路径(表示为边缘索引)。

For example for graph like that:例如对于这样的图:

       1
      /  \
(i=2)/    \(i=1)
    /      \
   2       3
           /\
          /  \
    (i=3)/    \(i=4)
        /      \
       4        5

I would like to have something like this:我想要这样的东西:

vector< vector<int> > roads = {{},{},{2},{1},{1,3},{1,4};

because roads[0] does not exist, roads[1] too, and for every other we have path expressed as edge indexes.因为roads[0]不存在, roads[1]也不存在,并且对于每个其他路径,我们都将路径表示为边缘索引。

EDIT编辑

In other words what I want to do: For every vertex in a given tree I want to know a path from root to this vertex.换句话说,我想做什么:对于给定树中的每个顶点,我想知道从根到该顶点的路径。 Every edge in this tree has its own number, so path would be expressed as a vector or set (for simplicity's sake, I don't care at all about the order of edges).这棵树中的每条边都有自己的编号,因此路径将表示为向量或集合(为简单起见,我根本不关心边的顺序)。

"graph with no cycles" is also known as a tree. “无环图”也称为树。

You want to have a list with all the sequences of edge labels that represent a path from root to some vertex?您想要一个包含所有边标签序列的列表,这些边标签表示从根到某个顶点的路径?

Pseudocode for a traversal (I guess this would qualify as a preorder traversal):遍历的伪代码(我想这可以作为preorder遍历):

void collect(node, //current node
    labels, //labels of edges leading to node
    &paths //all the paths collected so far, writeable, contains results
) {
    paths.add(labels);
    foreach ((neighbor_node, edge_name) in (unvisited neighbors of node)) {
        labels.add(edge_name);
        collect(neighbor_node, labels, paths);
        labels.remove(edge_name);                
    }
}

start with collect(root, empty_list, empty_list);

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

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