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

后端 未结 6 901
轮回少年
轮回少年 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:46

    This works. Assuming that visited flag is not there in Node. If isVisited is available, then there no need to tracker Map.

    // k is depth, result should not contain initialNode.
    public static Collection bfsWithK_Depth(Node initialNode, int k) {
    
        if (initialNode == null || k <= 0) {
            return new ArrayList<>();
        }
    
        Queue q = new LinkedList<>();
        q.add(initialNode);
        Map tracker = new HashMap(); // no need if there is visited flag.
        Collection result = new ArrayList<>();
    
        while (!q.isEmpty()) { // Q will be filled only with eligible nodes
            --k ;
            Node node = q.remove();
            List neighbor = node.getNeighbor();
            for (Node n : neighbor) {
                if (tracker.get(n) == null && k > 0) {
                    q.add(n);
                }
                if (tracker.get(n) == null) { 
                    tracker.put(n, n); 
                    result.add(n); // visit this node
                }
            }
    
        }
        return result;
    }
    

提交回复
热议问题