图的遍历

from collections import defaultdict
d = defaultdict(list)
n = int(input())
for i in range(n-1):
    a,b = map(int,input().split())
    d[a].append(b)
    d[b].append(a)
#print(d)
visited = defaultdict(bool)
visited[1]=True
lenth = 0
stack = [1]
while stack:
    next_layer = []
    while stack: #explore current layer stack
        node = stack.pop()
        for nex in d[node]:#add all next layer nodes of current node to next_layer
            if not visited[nex]:
                next_layer.append(nex)
                visited[nex]=True
    stack = next_layer #set current layer as next_layer
    lenth +=1 #layer +1 
print(2*(n-1)-lenth+1) # lenth add 1 when next_layer is empty in last loop


全部评论

相关推荐

CrazyBucket:我今天下午也做梦在招聘会上面试一家小厂,给自己气笑了
点赞 评论 收藏
分享
三年之期已到我的offer快到碗里来:9硕都比不上9本
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务