python---BFS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python---BFS相关的知识,希望对你有一定的参考价值。

 

#1

# here is a list of edges:
T = [(Bob,Eve),(Alice,Carol),(Eve,Frank),(Alice,Doug),(Frank,Ginger),          (Eve,Howard),(Carol,Irene),(Frank,Jeff),(Doug,Kathy),(Bob,Luis),          (Alice,Bob),(Bob,Mabel),(Ginger,Norm),(Howard,Oprah),(Carol,Peter),          (Kathy,Queen),(Mabel,Ursala),(Luis,Ronald),(Ginger,Sarah),(Irene,Tom),          (Jeff,Vince),(Peter,Wanda),(Oprah,Xanthia),(Norm,Yaakov),(Luis,Zandra)]

print (T has,len(T),edges)
vertices = set()
for edge in T:
    s,t = edge
    vertices.add(s)
    vertices.add(t)
print (T has,len(vertices),vertices)

 

#2

So this could be a tree. Now lets compute the number of parents for each vertex. The result confirms that we indeed have a tree and that the root is Alice (right?).

np = {}
for v in vertices:
    np[v] = 0
for parent,child in T:
    np[child] += 1
print (np)

Yes.

We now construct a dictionary of pairs (p,c) where p is the parent of the list of children c

#3

adjacency_map = {}
for v in vertices:
    adjacency_map[v] = []
for p,c in T:
    adjacency_map[p].append(c)

print ("node and children:")
for p in adjacency_map:
    print (p, ":", adjacency_map[p])

print ()
print (adjacency_map)

 

print (5*"Hello!")

 

#4 

做DFS,相当于树的前序遍历,python写起来相当简洁.DFS是遇到深度更深的节点立马去执行, 而不是像BFS一样拖着,加入队列,直到无法同层遍历时才选择深入(层序遍历).

# A recursive Depth-First traversal of a tree defined by an adjacency_map
def print_tree_depth_first(parent, adjacency_map, level=0):
    print (level*  , parent)
    children = adjacency_map[parent]
    for child in children:
        print_tree_depth_first(child, adjacency_map, level+1)

root = Alice
print_tree_depth_first(root, adjacency_map)

 

BFS

from collections import deque 

# breadth-first traversal using a queue
def print_tree_breath_first(root, adjacency_map):
    Q = deque()
    Q.append(root)
    while len(Q)>0:
        p = Q.popleft()
        print (p)
        children = adjacency_map[p]
        for child in children:
            Q.append(child)

print_tree_breath_first("Alice", adjacency_map)

 

修改成如下打印格式:

1: Alice
2: Carol Doug Bob
3: ...

 



以上是关于python---BFS的主要内容,如果未能解决你的问题,请参考以下文章

python BFS(宽度优先搜索算法) - 的Python

Python BFS 695. 岛屿的最大面积

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?