How to implement a breadth first search to a certain depth?

后端 未结 6 972
轮回少年
轮回少年 2021-02-04 07:08

I understand and can easily implement BFS.

My question is, how can we make this BFS limited to a certain depth? Suppose, I just need to go 10 level deep.

6条回答
  •  名媛妹妹
    2021-02-04 07:41

    For future readers, look at this example of the algorithm described above. This implementation will monitor how many nodes the following level contains. In doing so, the implementation is able to keep track of the current depth.

    void breadthFirst(Node parent, int maxDepth) {
    
      if(maxDepth < 0) {
        return;
      }
    
      Queue nodeQueue = new ArrayDeque();
      nodeQueue.add(parent);
    
      int currentDepth = 0, 
          elementsToDepthIncrease = 1, 
          nextElementsToDepthIncrease = 0;
    
      while (!nodeQueue.isEmpty()) {
        Node current = nodeQueue.poll();
        process(current);
        nextElementsToDepthIncrease += current.numberOfChildren();
        if (--elementsToDepthIncrease == 0) {
          if (++currentDepth > maxDepth) return;
          elementsToDepthIncrease = nextElementsToDepthIncrease;
          nextElementsToDepthIncrease = 0;
        }
        for (Node child : current.children()) {
          nodeQueue.add(child);
        }
      }
    
    }
    
    void process(Node node) {
      // Do your own processing here. All nodes handed to
      // this method will be within the specified depth limit.
    }    
    

提交回复
热议问题