通用性的图遍历函数

清单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]

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/zhang_xiaomeng/article/details/73163863
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞