清单5-6 通用性的图遍历函数
def traverse(G,s,qtype=set()):
S,Q=set(),qtype()
Q.add(s)
while Q:
u=Q.pop()
if u in S:continue
S.add(u)
for v in G[u]:
Q.add(v)
yield u
class stack(list):
add=list.append
if __name__=="__main__":
a, b, c, d, e, f, g, h, i= range(9)
N = [
{b, c, d}, # a
{a, d}, # b
{a,d}, # c
{a,b,c}, # d
{g,f}, # e
{e,g}, # f
{e,f}, # g
{i}, # h
{h} #i
]
G=[{b,c,d,e,f},#a
{c,e},#b
{d},#c
{e},#d
{f},#e
{c,g,h},#f
{f,h},#g
{f,g}#h
]
g=list(traverse(G,0,stack))
运行:
>>> g
[0, 5, 7, 6, 2, 3, 4, 1]