无向图-广度优先搜索和深度优先搜索
程序员文章站
2022-05-23 10:06:42
...
深度优先遍历简称DFS(Depth First Search),广度优先遍历简称BFS(Breadth First Search),它们是遍历图当中所有顶点的两种方式。
深度优先一般是解决连通性问题,而广度优先一般是解决最短路径问题
代码实现
import queue
class Graph:
#所有节点信息
nodeAll = []
#记录节点是否已访问 0否 1是
visited = []
#所有的边
edge = []
#节点数量
nodeNum = 0
#构造方法,初始化整个无向图
def __init__(self, nodeAll):
self.nodeAll = nodeAll
self.nodeNum = len(nodeAll)
#初始化所有节点都未访问
self.visited = [0] * self.nodeNum
#创建一个二维数据,是浅拷贝,每一维的数组都是指向同一个内容地址,会有问题
#test = [[0] * nodeNum] * nodeNum
#test[0][1] = 1
#创建一个二维数组,每次都会创建一个新的数组
self.edge = [([0] * self.nodeNum) for i in range(self.nodeNum)]
#添加边
def addEdge(self, v1, v2):
self.edge[v1][v2] = 1
self.edge[v2][v1] = 1
#深度优先搜索
def dfs(self, v0):
print('===',self.nodeAll[v0])
#标记当前节点已被访问
self.visited[v0] = 1
for j in range(self.nodeNum):
#如果当前节点有与之相邻的边,并且边的另一个节点没有被访问过
if self.edge[v0][j] == 1 and self.visited[j] == 0:
self.dfs(j)
#广度优先搜索
def bfs(self):
self.visited = [0] * self.nodeNum
#初始化一个队列,先进先出
que = queue.Queue(0)
for i in range(self.nodeNum):
#如果当前节点没有被访问过
if(self.visited[i] == 0):
self.visited[i] = 1
#将当前节点放入队列
que.put(i)
#队列不为空
while(not que.empty()):
#取出第一个元素
curr = que.get()
print('===',self.nodeAll[curr])
for j in range(self.nodeNum):
# 如果当前节点有与之相邻的边,并且边的另一个节点没有被访问过
if self.edge[curr][j] == 1 and self.visited[j] == 0:
self.visited[j] = 1
que.put(j)
def test1():
nodes = ['节点0', '节点1', '节点2', '节点3', '节点4', '节点5', '节点6']
graph = Graph(nodes)
graph.addEdge(0, 2)
graph.addEdge(0, 1)
graph.addEdge(0, 3)
graph.addEdge(2, 4)
graph.addEdge(1, 4)
graph.addEdge(1, 5)
graph.addEdge(3, 5)
graph.addEdge(4, 6)
graph.addEdge(5, 6)
# 初始化无向图
print('=====初始化无向图=====')
print(graph.edge)
print('=====深度优先搜索=====')
graph.dfs(0)
print('=====广度优先搜索=====')
graph.bfs()
def test2():
nodes = ['节点0','节点1', '节点2', '节点3', '节点4', '节点5', '节点6', '节点7', '节点8']
graph = Graph(nodes)
graph.addEdge(0, 1)
graph.addEdge(0, 7)
graph.addEdge(1, 2)
graph.addEdge(1, 4)
graph.addEdge(2, 3)
graph.addEdge(3, 4)
graph.addEdge(3, 5)
graph.addEdge(5, 6)
graph.addEdge(5, 7)
graph.addEdge(7, 8)
# 初始化无向图
print('=====初始化无向图=====')
print(graph.edge)
print('=====深度优先搜索=====')
graph.dfs(1)
print('=====广度优先搜索=====')
graph.bfs()
#测试
if(__name__ == '__main__'):
test2()
参考资料:
上一篇: 无向图的广度优先搜索