標籤:而不是 修改 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