博客
关于我
【Lintcode】291. Second Diameter
阅读量:188 次
发布时间:2019-02-28

本文共 2355 字,大约阅读时间需要 7 分钟。

一棵树型无向带权图的次大直径是指所有两点间距离中的第二长,包括相同长度的路径。为了求解次大直径,我们可以参考以下步骤:

1. 求直径的两个端点

首先,使用广度优先搜索(BFS)从任意节点出发,找到最远的节点u。接着,再次从u出发,进行BFS找到最远的节点v。这样,u和v就是直径的两个端点。

2. 计算次大直径

从u出发,排除v,进行BFS,找到最远的节点a。同样地,从v出发,排除u,进行BFS,找到最远的节点b。次大直径即为a到u的距离与b到v的距离中的较大者。

3. 算法正确性

根据树的性质,任何最长路径都必然连接直径的两个端点。因此,从任意节点出发的最远点必定是直径的一个端点。

4. 代码实现

import java.util.*;public class Solution {    private long res;    public long getSecondDiameter(int[][] edge) {        int n = edge.length + 1;        Map
> graph = buildGraph(edge); int far1 = bfs(0, graph, -1, new boolean[n]); int far2 = bfs(far1, graph, -1, new boolean[n]); bfs(far1, graph, far2, new boolean[n]); bfs(far2, graph, far1, new boolean[n]); return res; } private int bfs(int v, Map
> graph, int u, boolean[] visited) { Queue
queue = new LinkedList<>(); queue.offer(new long[]{v, 0}); visited[v] = true; int farV = v; long farDis = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { long[] cur = queue.poll(); int nextV = (int) cur[0]; if (graph.containsKey(nextV)) { for (int[] next : graph.get(nextV)) { if (next[0] != u && !visited[next[0]]) { if (next[1] + cur[1] > farDis) { farDis = next[1] + cur[1]; farV = next[0]; } visited[next[0]] = true; queue.offer(new long[]{next[0], next[1] + cur[1]}); } } } } } if (u != -1) { res = Math.max(res, farDis); } return farV; } private Map
> buildGraph(int[][] edges) { Map
> graph = new HashMap<>(); for (int[] edge : edges) { graph.putIfAbsent(edge[0], new ArrayList<>()); graph.get(edge[0]).add(new int[]{edge[1], edge[2]}); graph.putIfAbsent(edge[1], new ArrayList<>()); graph.get(edge[1]).add(new int[]{edge[0], edge[2]}); } return graph; }}

5. 时空复杂度

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

该算法通过两次BFS找到直径,再从直径端点出发计算次大直径,确保了在树结构下的高效计算。

转载地址:http://adjs.baihongyu.com/

你可能感兴趣的文章
Node.js 8 中的 util.promisify的详解
查看>>
node.js debug在webstrom工具
查看>>
Node.js RESTful API如何使用?
查看>>
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 模块系统的原理、使用方式和一些常见的应用场景
查看>>
Node.js 的事件循环(Event Loop)详解
查看>>
node.js 简易聊天室
查看>>
Node.js 线程你理解的可能是错的
查看>>