【问题标题】:Tracking depth in a non-recursive breadth first search非递归广度优先搜索中的跟踪深度
【发布时间】:2013-08-02 03:35:30
【问题描述】:

我有以下算法进行广度优先搜索:

q := []
q.append(root node of tree)
while q:
    n := q.pop(0)
    yield n
        if n has children:
            c := children of node
            for i in c:
                q.append(i)

1) 如何扩展它以跟踪当前深度? 2) 这个扩展是否适用于深度优先搜索的类似算法,队列q 被堆栈替换?

【问题讨论】:

    标签: language-agnostic tree breadth-first-search


    【解决方案1】:

    为了扩展 larsmans 的出色回答,下面是我的 代码,用于深度受限的广度优先二叉树遍历。

    (代码假设 Node 不包含深度信息,并在入队之前将每个节点包装在 NodeAndDepth 结构中。)

    struct NodeAndDepth {
        NodeAndDepth(Node *n, unsigned int d) : node(n), depth(d) {}
        Node *node;
        unsigned int depth;
    };
    
    void traverseBreadthFirst_WithDepthLimit(Node *root, unsigned int maxDepth) {
        if (maxDepth == 0 || root == NULL) { return; }
    
        std::queue<NodeAndDepth> q;
        q.push(NodeAndDepth(root, 1));
    
        while (!q.empty()) {
            NodeAndDepth n = q.front(); q.pop();
    
            // visit(n.node); 
            // cout << n.depth << ": " << n.node->payload << endl;
    
            if (n.depth >= maxDepth) { continue; }
    
            if (n.node->left != NULL) {
                q.push(NodeAndDepth(n.node->left, n.depth + 1));
            }
    
            if (n.node->right != NULL) {
                q.push(NodeAndDepth(n.node->right, n.depth + 1));
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      只需将深度与节点一起存储,并在每次生成节点的子节点时递增。

      q := [(root, 0)]
      while q:
          n, depth := q.pop()
          yield n, depth
          if n has children:
              c := children of n
              for i in c:
                  q.append(i, depth + 1)
      

      这个想法扩展到 DFS 和启发式搜索。

      【讨论】:

      • 完美拯救我长时间的调试
      猜你喜欢
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多