Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 749
user1220022 Avatar asked Apr 21 '12 10:04

user1220022


People also ask

How do you find depth in BFS?

Let the variable visited equal 0. Each time a node is visited, increment visited by 1. Each time visited is incremented, calculate the node's depth as depth = round_up(log2(visited + 1))

Which technique is the implementation of Breadth First Search?

Following are the implementations of simple Breadth-First Traversal from a given source. The implementation uses an adjacency list representation of graphs. STL's list container stores lists of adjacent nodes and the queue of nodes needed for BFS traversal.

Is Breadth First Search better than depth first search?

BFS is better when target is closer to Source. DFS is better when target is far from source. As BFS considers all neighbour so it is not suitable for decision tree used in puzzle games. DFS is more suitable for decision tree.

What problem can BFS solve whilst depth first search DFS Cannot?

BFS can be used to find the shortest path, with unit weight edges, from a node (origional source) to another. Whereas, DFS can be used to exhaust all the choices because of its nature of going in depth, like discovering the longest path between two nodes in an acyclic graph.


1 Answers

You can do this with constant space overhead.

BFS has the property that unvisited nodes in the queue all have depths that never decrease, and increase by at most 1. So as you read nodes from the BFS queue, you can keep track of the current depth in a single depth variable, which is initially 0.

All you need to do is record which node in the queue corresponds to the next depth increase. You can do this simply by using a variable timeToDepthIncrease to record the number of elements that are already in the queue when you insert this node, and decrementing this counter whenever you pop a node from the queue.

When it reaches zero, the next node you pop from the queue will be at a new, greater (by 1) depth, so:

  • Increment depth
  • Set pendingDepthIncrease to true

Whenever you push a child node on the queue, first check whether pendingDepthIncrease is true. If it is, this node will have greater depth, so set timeToDepthIncrease to the number of nodes in the queue before you push it, and reset pendingDepthIncrease to false.

Finally, stop when depth exceeds the desired depth! Every unvisited node that could appear later on must be at this depth or greater.

[EDIT: Thanks commenter keyser.]

like image 82
j_random_hacker Avatar answered Oct 06 '22 12:10

j_random_hacker