Performing Breadth First Search recursively

后端 未结 21 2529
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?

Is it possible using only the call-stack

21条回答
  •  执念已碎
    2020-11-28 01:49

    Here's a python implementation:

    graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}
    
    def bfs(paths, goal):
        if not paths:
            raise StopIteration
    
        new_paths = []
        for path in paths:
            if path[-1] == goal:
                yield path
    
            last = path[-1]
            for neighbor in graph[last]:
                if neighbor not in path:
                    new_paths.append(path + [neighbor])
        yield from bfs(new_paths, goal)
    
    
    for path in bfs([['A']], 'D'):
        print(path)
    

提交回复
热议问题