python---BFS

來源:互聯網
上載者:User

標籤:而不是   修改   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] = 0for parent,child in T:    np[child] += 1print (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_mapdef 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 queuedef 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.