图数据结构有两种经典的遍历方式: 广度优先搜索和深度优先搜索
这里以广度优先搜索为例
class Person: def __init__(self, name): self.name = name self.friends = [] self.visited = False def add_friend(self, friend): self.friends.append(friend) def display_network(self): # 记下每个访问过的人, 以便算法完结后能重置他们的visited属性为false to_reset = [self] # 创建一个开始就含有根顶点的队列 queue = [self] self.visited = True while len(queue): # 设出队的顶点为当前顶点 current_vertex = queue.pop(0) print(current_vertex.name, end=' ') # 将当前顶点的所有未访问的邻接点加入队列 for friend in current_vertex.friends: if not friend.visited: to_reset.append(friend) queue.append(friend) friend.visited = True # 算法完结时,将访问过的结点的visited属性重置为false for node in to_reset: node.visited = False if __name__ == '__main__': # 起步定点 alice = Person('Alice') # 一度联系人 bob = Person('Bob') candy = Person('Candy') derek = Person('Derek') elaine = Person('Elaine') # 二度联系人 fred = Person('Fred') gina = Person('Gina') # 三度联系人 helen = Person('Helen') irena = Person('Irena') alice.add_friend(bob) alice.add_friend(candy) alice.add_friend(derek) alice.add_friend(elaine) bob.add_friend(alice) bob.add_friend(fred) candy.add_friend(alice) derek.add_friend(alice) derek.add_friend(gina) elaine.add_friend(alice) fred.add_friend(bob) fred.add_friend(helen) gina.add_friend(derek) gina.add_friend(irena) helen.add_friend(fred) irena.add_friend(gina) alice.display_network() # 打印结果:Alice Bob Candy Derek Elaine Fred Gina Helen Irena