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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
depthvariable, 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
timeToDepthIncreaseto 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:
depthpendingDepthIncreaseto trueWhenever you push a child node on the queue, first check whether
pendingDepthIncreaseis true. If it is, this node will have greater depth, so settimeToDepthIncreaseto the number of nodes in the queue before you push it, and resetpendingDepthIncreaseto false.Finally, stop when
depthexceeds the desired depth! Every unvisited node that could appear later on must be at this depth or greater.[EDIT: Thanks commenter keyser.]