深度优先,广度优先搜素
深度优先搜索是一种遍历方式,不局限在树或是图中,还可以用其解决很多层级关系的问题。
网上关于dfs介绍代码都很多了,但个人感觉不够直观,为了简洁性,使用最直观的python描述。
数据结构:
class Node:
data = ""
neighbors = []
def __init__(self, data, neighbors=None) -> None:
if neighbors is None:
neighbors = []
self.data = data
self.neighbors = neighbors
DFS
递归遍历
def access(cur: Node):
print(cur.data)
def search_re(cur: Node):
visisted = set()
def _search(cur: Node):
nonlocal visisted
access(cur)
visisted.add(cur)
for neighbor in cur.neighbors:
if neighbor not in visisted:
_search(neighbor)
_search(cur)
非递归遍历
def search_it(cur: Node):
visisted = set()
stack = []
stack.append(cur)
while stack:
cur = stack.pop()
if cur not in visisted:
access(cur)
visisted.add(cur)
for neighbor in cur.neighbors:
if neighbor not in visisted:
stack.append(neighbor)
BFS
def bfs(cur: Node):
visisted = set()
queue = deque()
queue.append(cur)
while queue:
cur = queue.popleft()
if cur not in visisted:
access(cur)
visisted.add(cur)
for neighbor in cur.neighbors:
if neighbor not in visisted:
queue.append(neighbor)
测试
# 构建graph
# a- b - d
# \ | |
# c - e
a, b, c, d, e = Node("a"), Node("b"), Node("c"), Node("d"), Node("e")
a.neighbors.extend([b, c])
b.neighbors.extend([a, c, d])
c.neighbors.extend([a, b, e])
d.neighbors.extend([b, e])
e.neighbors.extend([c, d])
# search_it(a) # a c e d b
# search_re(a) # a b c e d
# bfs(a) # a b c d e
参考
http://web.cs.unlv.edu/larmore/Courses/CSC477/bfsDfs.pdf