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

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

    If you dont want to have a class node (and add a variable depth to your node) then you can have two maps for distance and visitedNodes or a 2d Array where each row is a node and column1:depth, column2: visited. Of course you can track both with one map (where Node is an instance of the class or int,String etc and Depth is an int that represent the Depth of the Node from the root node). if map contains a node (O(1) cost) then it is visited, if not proceed and add it to map with depth of current node +1.

    public static void BfsToDepth(graph graphDb, Node rootNode, int depth) {
        if(depth<1)
           return;
        Queue queue = new LinkedList<>();
        ResourceIterator nodesIterator = graphDb.getAllNodes().iterator();
        LinkedHashMap visited = new LinkedHashMap<>();
        LinkedHashMap distance = new LinkedHashMap<>();
        // Start: Bfs Init Step
        if (nodesIterator.hasNext() == true) {
            while (nodesIterator.hasNext()) {
                Node currentNode = nodesIterator.next();
                visited.put(currentNode, false);
                distance.put(currentNode, Integer.MAX_VALUE);
            }
        } else {
            System.out.println("No nodes found");
        }
        // End: Bfs Init Step 
    
        distance.put(rootNode, 0);
        visited.put(rootNode, true);
        queue.add(rootNode);
        Node current = null;
    
        while (queue.isEmpty() == false) {
            current = queue.poll();
            if (distance.get(current) <= depth) {
                Iterator relationships = current.getRelationships().iterator();
                if (relationships.hasNext() == true) {
                    while (relationships.hasNext()) {
                        Relationship relationship = relationships.next();
                        Node adjacent = relationship.getOtherNode(current);
    
                        if (visited.get(adjacent) == false) {
                            /*if you want to print the distance of each node from root then 
                            System.out.println("len: "+ (distance.get(current) + 1)+" to: "+ adjacent);*/
                            distance.put(adjacent, (distance.get(current) + 1));
                            visited.put(adjacent, true);
                            queue.add(adjacent);
                        }
                    }
                }
            }
        }
    }
    

提交回复
热议问题