BFS和DFS
-
BFS核心点是用队列存放当前搜索的点
-
用在有环图的时候需要存放遍历过的点
queue = [start] visited = set([start]) while queue: node = queue.pop(0) for n in get_near_nodes(node): if n not in visited: queue.append(n) visited.add(n)
-
DFS使用栈/直接用递归来进行遍历
stack = [start] visited = set([start]) while stack: node = stack.pop() for n in get_near_nodes(node): if n not in visited: stack.append(n) visited.add(n)
网友评论