类似于邻接表的Python图论练习自测

0 Comments

class Node:
    def __init__(self,name):
        self.name = name
        self.nexts = set()
        self.visited = False
                
    def add_next(self,node):
        self.nexts.add(node)

    def add_nexts(self,*n):
        for node in n:
            self.add_next(node)

class Graph:
    def __init__(self,*n):
        """图就是很多节点和边的集合,这里没有传边的集合"""
        self.nodes = set(n)

    def traverse(self,node):
        """从node这个节店遍历图中的每一个节点"""
        node.visited = True
        print(node.name,end='')
        for n in node.nexts:
            if n.visited==False:
                self.traverse(n)
            
    
a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')
f = Node('f')
g = Node('g')

a.add_nexts(b,c,d)
b.add_nexts(a,f)
c.add_nexts(a,e,f)
d.add_nexts(a,e,g)
e.add_nexts(d,c,g)
f.add_nexts(b,c,g)
g.add_nexts(f,e,d)

tu = Graph(a,b,c,d,e,f,g)
tu.traverse(a)

发表评论