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

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

    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
    

提交回复
热议问题