import collections class graph: def __init__(self,point,graph): self.graph=graph #传入的临接表 self.point=point #数组 self.visited=[0 for _ in range(len(graph))] def bfs(self,n): queue=collections.deque([n]) #第一个元素入队列 self.visited[n]=1 while queue: node_index=queue.popleft() #从队列左边弹出 print(self.point[node_index]) #打印当前队列弹出点的值 for i in range(len(self.graph)): if self.graph[node_index][i]==1 and self.visited[i]==0: #相邻且未被访问 queue.append(i) self.visited[i]=1 test= [[0,1,0,1,1], [1,0,1,0,0], [0,1,0,0,0], [1,0,0,0,1], [1,0,0,1,0]] point=[1,2,3,4,5] graph(point,test).bfs(0)