赞
踩
1、宽度优先搜索:
宽度优先搜索算法(Breadth First Search,BSF),思想是:
如上图的BFS访问顺序为:A->B->C->D->E->F
2、深度优先搜索:
图的深度优先搜索(Depth First Search, DFS),和树的前序遍历非常类似。
它的思想:
如上图的BFS访问顺序为:A->B->D->E->C->F
# -*- coding: utf-8 -*- from collections import deque # 线性表的模块 # 首先定义一个创建图的类,使用邻接矩阵 class Graph(object): def __init__(self, *args, **kwargs): self.order = [] # visited order self.neighbor = {} def add_node(self, node): key, val = node if not isinstance(val, list): print('节点输入时应该为一个线性表') # 避免不正确的输入 self.neighbor[key] = val # 宽度优先算法的实现 def BFS(self, root): #首先判断根节点是否为空节点 if root != None: search_queue = deque() search_queue.append(root) visited = [] else: print('root is None') return -1 while search_queue: # search_queue =[B,C] person = search_queue.popleft()# B # search_queue =[C] self.order.append(person)# [A, B] if (not person in visited) and (person in self.neighbor.keys()): # self.neighbor[person] = [D, E] # search_queue [C] search_queue += self.neighbor[person] # search_queue [C, D, E] 从左往右宽度优先 visited.append(person) # 深度优先算法的实现 def DFS(self, root): # 首先判断根节点是否为空节点 if root != None: search_queue = deque() search_queue.append(root) visited = [] else: print('root is None') return -1 while search_queue: # search_queue =[B,C] person = search_queue.popleft() # search_queue=[C] self.order.append(person) # order = [A,B] if (not person in visited) and (person in self.neighbor.keys()): tmp = self.neighbor[person]#[D, E] tmp.reverse()# tmp 因为下面打算左添加 # search_queue=[C] # 左边添加 tmp for index in tmp: search_queue.appendleft(index) # search_queue =[D,E,C] 从左下到右,深度优先 visited.append(person)# visited= [A, B] def clear(self): self.order = [] def node_print(self): for index in self.order: print(index, end=' ') if __name__ == '__main__': # 创建一个二叉树图 g = Graph() g.add_node(('A', ['B', 'C'])) g.add_node(('B', ['D', 'E'])) g.add_node(('C', ['F'])) # 进行宽度优先搜索 g.BFS('A') print('宽度优先搜索:') print(' ', end=' ') g.node_print() g.clear() # 进行深度优先搜索 print('\n\n深度优先搜索:') print(' ', end=' ') g.DFS('A') g.node_print() print()
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。