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.
One simple way is to use a dictionary to keep track of the depth of each node when exploring the graph. Then just break if the max depth is reached.
Example in Python:
from collections import deque
def bfs_maxdepth(graph, start, maxdepth):
queue = deque([start])
depths = {start: 0}
while queue:
vertex = queue.popleft()
if depths[vertex] == maxdepth:
break
for neighbour in graph[vertex]:
if neighbour in depths:
continue
queue.append(neighbour)
depths[neighbour] = depths[vertex] + 1
return depths