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

问题描述

我知道如何在C ++中实现深度优先搜索算法,但是我需要一个“扩展版本”。所以,我有一张地图

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

对于任何顶点,它将返回一个映射,其中相邻顶点为键,并且(对于我的程序很重要)边缘索引为值。树的根是第一(1)个顶点。所以,这是我的代码

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();
}

我需要做的是创建一个向量向量,其中每个顶点都有一条完整的路径(表示为边缘索引)。

例如这样的图形:

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

我想要这样的东西:

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

因为roads[0]不存在,roads[1]也不存在,并且我们彼此之间都将路径表示为边缘索引。

编辑

换句话说,我想做什么: 对于给定树中的每个顶点,我想知道从根到该顶点的路径。该树中的每个边缘都有自己的编号,因此路径将表示为向量或集合(为简单起见,我根本不在乎边缘的顺序)。

解决方法

“无周期图”也称为树。

您是否想要一个包含所有边缘标签序列的列表,这些序列代表从根到某个顶点的路径?

遍历的伪代码(我想这将成为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);