码迷,mamicode.com
首页 > 编程语言 > 详细

python---BFS

时间:2017-10-28 17:42:05      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:而不是   修改   tom   blog   car   遍历   res   ...   logs   

 

#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

标签:而不是   修改   tom   blog   car   遍历   res   ...   logs   

原文地址:http://www.cnblogs.com/kprac/p/7747243.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!