BFS&Python

来源:互联网 发布:什么软件有淘宝优惠卷 编辑:程序博客网 时间:2024/06/05 08:20
# 邻接矩阵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)# 起点记录为 Truediscovered[0] = True# L[0] = [0]  L[0]只包含一个初始节点L = []L.append([0])# 记录层数i = 0edges = [] # 记录搜索树上的边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)
原创粉丝点击