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

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

    The easy Idea for keeping track of the depth is to add "NULL" to the Queue every time you go a level deep. As soon as you poll a null from the queue, Increase your level counter by 1 and add another 'null' to the Queue. If you get two consecutive nulls you can exit from the loop.

    q.offer(user);
    q.offer(null);
    
    user.setVisited(true);
    
    while(!q.isEmpty()){
    
        User userFromQ = q.poll();
    
        if(userFromQ == null){
            level++;
            q.offer(null);
            if(q.peek()==null)
                break;
            else
                continue;
        }
    

提交回复
热议问题