【问题标题】:"Extended" depth-first search in C++C++ 中的“扩展”深度优先搜索
【发布时间】:2020-11-01 15:25:57
【问题描述】:

我知道如何在 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},{1,4};

因为roads[0] 不存在,roads[1] 也不存在,并且对于其他每个我们都有表示为边缘索引的路径。

编辑

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

【问题讨论】:

  • 您要解决什么问题?这里到底有什么问题? roads(算法的输入)和预期输出是什么?
  • 这听起来像XY Problem
  • @ggorlen 不,roads 不是输入。
  • @PaulMcKenzie 非常感谢您提供这方面的信息。我意识到这确实是一个 XY 问题,所以请看 EDIT。
  • 您的编辑并没有解释所有这些的目的。为什么需要这样做?只是为了好玩还是你想解决某种问题?请提供上下文。 “问题”/算法(无论是什么)的输入是什么? tree 在顶部进行了讨论,但我认为以后不再使用它。

标签: c++ algorithm depth-first-search shortest-path


【解决方案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);

【讨论】:

  • 为了完全准确,没有循环的图是一片森林,但我们不要在这里讨论技术细节......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多