图的遍历

def breadth_first_search(graph,root):
if not root:
return
traverse = [root]
my_queue = [root]
while my_queue:
next = my_queue.pop(0)
for current in graph[next]:
if current not in traverse:
traverse.append(current)
my_queue.append(current)
return traverse
def depth_first_search(graph,root):
if not root:
return
stack = [root]
traverse = [root]
while stack:
next = stack.pop()
for current in graph[next]:
if current not in traverse:
stack.append(next)
stack.append(current)
traverse.append(current)
break
return traverse
def depth_first_search_recursion(graph,root):
traverse = [root]
def dfs(graph,root,traverse):
if not root:
return
for next in graph[root]:
if next not in traverse:
traverse.append(next)
dfs(graph,next,traverse)
return traverse
return dfs(graph,root,traverse)
if __name__ == '__main__':
graph = {
'A': ['B', 'F'],
'B': ['C', 'I', 'G'],
'C': ['B', 'I', 'D'],
'D': ['C', 'I', 'G', 'H', 'E'],
'E': ['D', 'H', 'F'],
'F': ['A', 'G', 'E'],
'G': ['B', 'F', 'H', 'D'],
'H': ['G', 'D', 'E'],
'I': ['B', 'C', 'D'],
}
print(breadth_first_search(graph,'A'))
print(depth_first_search(graph,'A'))
print(depth_first_search_recursion(graph,'A'))