BFS&Python

# 邻接矩阵
graph = [
    [0,1,1,0,0,0,0,0],
    [1,0,1,1,1,0,0,0],
    [1,1,0,0,1,0,1,1],
    [0,1,0,0,0,0,0,0],
    [0,1,1,0,0,1,0,0],
    [0,0,0,0,1,0,0,0],
    [0,0,1,0,0,0,0,0],
    [0,0,1,0,0,0,0,0]
]
# 记录定点是否被到达
discovered = [False]*len(graph)
# 起点记录为 True
discovered[0] = True
# L[0] = [0] L[0]只包含一个初始节点
L = []
L.append([0])
# 记录层数
i = 0
edges = [] # 记录搜索树上的边
while len(L[i]) != 0:
    temp = []
    for node in L[i]: # 对这一层中的每一个节点进行遍
        for j in range(len(graph)): # 查找与其相邻的边
            if graph[i][j]: 
                if discovered[j] == False: # 另一个定点没有被访问过就加入i+1层
                    discovered[j] = True
                    temp.append(j)
                    edges.append((i,j))# 往搜索树中插入一条边
    i += 1
    L.append(temp)

for item in L:
    if len(item):
        print(item)
    原文作者:BFS
    原文地址: https://blog.csdn.net/qq_14998713/article/details/78885003
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞