基于python模拟bfs和dfs代码实例
程序员文章站
2022-06-09 16:48:00
bfs"""# @time : 2020/11/8# @author : jimou chen"""# 广搜def bfs(graph, start): queue = [start] # 先把起...
bfs
""" # @time : 2020/11/8 # @author : jimou chen """ # 广搜 def bfs(graph, start): queue = [start] # 先把起点入队列 visited = set() # 访问国的点加入 visited.add(start) while len(queue): vertex = queue.pop(0) # 找到队列首元素的连接点 for v in graph[vertex]: if v not in visited: queue.append(v) visited.add(v) # 打印弹出队列的该头元素 print(vertex, end=' ') if __name__ == '__main__': graph = { 'a': ['b', 'd', 'i'], 'b': ['a', 'f'], 'c': ['d', 'e', 'i'], 'd': ['a', 'c', 'f'], 'e': ['c', 'h'], 'f': ['b', 'h'], 'g': ['c', 'h'], 'h': ['e', 'f', 'g'], 'i': ['a', 'c'] } bfs(graph, 'a')
a b d i f c h e g
process finished with exit code 0
dfs
""" # @time : 2020/11/8 # @author : jimou chen """ # 深搜 def dfs(graph, start): stack = [start] visited = set() visited.add(start) while len(stack): vertex = stack.pop() # 找到栈顶元素 for v in graph[vertex]: if v not in visited: stack.append(v) visited.add(v) print(vertex, end=' ') if __name__ == '__main__': graph = { 'a': ['b', 'd', 'i'], 'b': ['a', 'f'], 'c': ['d', 'e', 'i'], 'd': ['a', 'c', 'f'], 'e': ['c', 'h'], 'f': ['b', 'h'], 'g': ['c', 'h'], 'h': ['e', 'f', 'g'], 'i': ['a', 'c'] } dfs(graph, 'e')
e h g f b a i d c
process finished with exit code 0
总结
很明显一个用了队列,一个用了栈
利用python语言优势,只需改动pop即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。