1. 解题思路
这一题的话算是一个拓扑树的题目?总之就是从树的叶子节点不断向上遍历,不断地删除已访问的叶子节点,并加入更新之后的新的叶子节点,这样我们就能得到树的最大深度,然后在遍历过程中我们考察其任意节点上的当前深度和已有深度的和的最大值,即为经过该节点的最大路径长度,遍历整张图,我们即刻获得整个树的深度和diameter。然后,我们要连接两个图的话,能够获得的最大路径长度就是两个图的深度之和加一。
由此,我们即可完成这道题目了。
2. 代码实现
给出python代码实现如下:
class Solution:
def minimumDiameterAfterMerge(self, edges1: List[List[int]], edges2: List[List[int]]) -> int:
def dfs(edges):
if edges == []:
return 0, 0
diameter = 0
graph = defaultdict(list)
deg = defaultdict(int)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
deg[u] += 1
deg[v] += 1
seen = set()
leafs = [u for u in deg if deg[u] == 1]
depth = defaultdict(int)
while leafs != []:
u = leafs.pop(0)
if u in seen:
continue
seen.add(u)
for v in graph[u]:
if v in seen:
continue
diameter = max(diameter, depth[v] + depth[u] + 1)
depth[v] = max(depth[v], depth[u]+1)
deg[v] -= 1
if deg[v] == 1:
leafs.append(v)
return max(depth.values()), diameter
depth1, diameter1 = dfs(edges1)
depth2, diameter2 = dfs(edges2)
return max(depth1 + depth2 + 1, diameter1, diameter2)
提交代码评测得到:耗时3216ms,占用内存93.4MB。
标签:Diameter,3203,diameter,int,graph,After,depth,leafs,deg From: https://blog.csdn.net/codename_cys/article/details/140083957