深度优先搜索
def depth_first_search(graph, start):
seen, current = set(), []
current.append(start)
while current:
u = current.pop()
if u in seen:
continue
seen.add(u)
current.extend(graph[u])
yield u
graph = {
'a': set('bcd'),
'b': set('ce'),
'c': set(),
'd': set('ce'),
'e': set(),
}
print(list(depth_first_search(graph, 'a'))) # ['a', 'b', 'e', 'c', 'd']
广度优先搜索
from collections import deque
def breadth_first_search(graph, start):
parents, current = {start: None}, deque([start])
while current:
u = current.popleft()
for v in graph[u]:
if v in parents:
continue
parents[v] = u
current.append(v)
return parents
graph = {
'a': set('bcd'),
'b': set('ce'),
'c': set(),
'd': set('ce'),
'e': set(),
}
print(breadth_first_search(graph, 'a'))
(最近更新:2019年05月31日)