美团2019秋招笔试—图的遍历

题目:

美团2019秋招笔试—图的遍历_第1张图片

思路:N个节点,N -1个边,且无向连通图,每次从1开始遍历,说明是生成树;则最长的边遍历一次,其他的边遍历两次,则能使得路程最短;首先求得最大深度m,然后就可以得到路程m + (N-1-m)*2;

美团2019秋招笔试—图的遍历_第2张图片

代码:

n =7
edge = [[1,2],[2,3],[2,4],[3,6],[6,7],[3,5]]

from collections import defaultdict

d = defaultdict(list)
for i in edge:
    d[i[0]].append(i[1])
    d[i[1]].append(i[0])

visited = [False] * (n + 1)
deep = [0] * (n + 1)
parent = [-1] * (n + 1)

def recursion(d, node, deep_tmp):
    deep_tmp += 1
    visited[node] = True
    if d[node] == []:
        return 
    for i in d[node]:
        if visited[i] == False:
            deep[i] = deep_tmp
            parent[i] = node
            recursion(d, i, deep_tmp)
recursion(d, 1, 0)
max_deep = max(deep)
print(max_deep + 2 * (n - 1 - max_deep))

 

你可能感兴趣的:(笔试记录)