Algorithm and data structure Lab7 Question1 find grith of undirected graph

实现一个函数:找一个无向图的girth. 参数为adjaceny lists of and graph. If no circle,return ‘inf’

这道题思路就是用对每个节点进行BFS: 用queue来实现. 记录下来每个节点的深度,每次用BFS遍历的时候,用一个seen(list)来保存遍历过的节点,再BFS过程中一旦发现了已经遍历过的节点,那么便可能存在circle,记录下来,这样通过对每个节点进行BFS便可以得到girth.
Hit:需要注意的是 在遍历过程中发现了一个已经在seen中的节点与此次遍历的节点存在一条arc,有可能是tree arc(也就是直接相连的,因此需要用一个list来存放所有的tree arc,以下是实现代码

def find_girth(adj_list):
    girth = float('inf') #初始化为inf,不要写在下面的for循环里面因为是要每次得到的circle长度比较来找最小的circle长度才是girth
    for v in range(len(adj_list)): #对每个节点都进行一次bfs
        tree = [] #tree用来记录tree arc.
        queue =[]
        seen = [] #seen 来记录访问过的边
        time = dict() #time 来记录每个节点的深度
        queue.append(v)
        time[v] = 0
        seen.append(v)
        while len(queue)!= 0:
            vertex = queue.pop(0)
            for i in adj_list[vertex]:
                if i not in seen:
                    seen.append(i)
                    queue.append(i)
                    time[i] = time[vertex] + 1
                    tree.append([vertex,i])
                elif i in seen and [vertex,i] not in tree and [i,vertex] not in tree:
                	#如果找到了一个已经遍历过的节点和该节点之间存在边 且该边不在tree里面则说明存在 circle
                    if time[i] == time[vertex]:#如果两点深度相同
                        circle_length = 2 * time[i] + 1
                        girth = circle_length if girth > circle_length else girth
                    else:#两个点深度不同的话,两点的距离只差1,因为用的是BFS逐层查找
                        circle_length = time[i] + time[vertex] + 1
                        girth = circle_length if girth > circle_length else girth
    return girth
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值