实现一个函数:找一个无向图的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