走遍无人区之深度优先搜索(DFS)和广度优先搜索(BFS)(二)
# -*- 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:
person = search_queue.popleft()
#self.order.append(person)
if person in self.order:
continue
else:
self.order.append(person)
if (not person in visited) and (person in self.neighbor.keys()):
search_queue += self.neighbor[person]
visited.append(person)
def node_print(self):
for index in self.order:
print(index, end=' ')
if __name__ == '__main__':
# 创建一个树状结构
g = Graph()
g.add_node(('1', ['0', '2']))
g.add_node(('0', ['5', '4']))
g.add_node(('5', ['3']))
g.add_node(('4', ['6']))
g.add_node(('2', ['4']))
# 进行广度优先搜索
g.BFS('1')
print('广度优先搜索:')
print(' ', end=' ')
g.node_print()
上述代码的运算结果如下所示:
广度优先搜索:
1 0 2 5 4 3 6
如何探索出一条最优路径,想必各位小伙伴也已经Get到了其中的思想精髓,是不是再也不怕在探索过程中没有水喝了呢,赶快动身继续前进吧!当然,在深度优先搜索和广度优先搜索算法这对好兄弟当中还蕴含着许许多多小思想、小方法,我们也将在后续逐渐详细介绍到。接下来,我们将得到前面几位兄弟的帮助,正是打开路径规划的探索之路啦!