当前位置: 首页 > news >正文

DeepSeek LeetCode 2642. 设计可以求最短路径的图类 Java实现

下面是 LeetCode 2642「设计可以求最短路径的图类」的 Java 实现。题目理解设计一个 Graph 类支持1. 初始化Graph(int n, int[][] edges) - n 个节点0 到 n-1edges 为有向边 (from, to, cost)2. 添加边addEdge(int[] edge) - 添加一条新边3. 求最短路径shortestPath(int node1, int node2) - 返回 node1 到 node2 的最短路径长度不存在返回 -1核心思路使用** Dijkstra 算法**由于需要动态添加边每次查询时运行 Dijkstra 即可n ≤ 100edges ≤ 100查询次数 ≤ 100复杂度可接受。完整实现代码ACjavaimport java.util.*;class Graph {private int n;private Listint[][] graph;public Graph(int n, int[][] edges) {this.n n;graph new ArrayList[n];for (int i 0; i n; i) {graph[i] new ArrayList();}for (int[] edge : edges) {addEdge(edge);}}public void addEdge(int[] edge) {int from edge[0];int to edge[1];int cost edge[2];graph[from].add(new int[]{to, cost});}public int shortestPath(int node1, int node2) {// 距离数组初始化为无穷大int[] dist new int[n];Arrays.fill(dist, Integer.MAX_VALUE);dist[node1] 0;// 优先队列存储 [距离, 节点]PriorityQueueint[] pq new PriorityQueue(Comparator.comparingInt(a - a[0]));pq.offer(new int[]{0, node1});while (!pq.isEmpty()) {int[] curr pq.poll();int currDist curr[0];int currNode curr[1];// 如果当前距离大于记录的距离跳过if (currDist dist[currNode]) {continue;}// 到达目标节点可以提前返回因为 Dijkstra 第一次弹出就是最短if (currNode node2) {return currDist;}// 遍历邻接边for (int[] neighbor : graph[currNode]) {int nextNode neighbor[0];int weight neighbor[1];int newDist currDist weight;if (newDist dist[nextNode]) {dist[nextNode] newDist;pq.offer(new int[]{newDist, nextNode});}}}return dist[node2] Integer.MAX_VALUE ? -1 : dist[node2];}}优化版本使用邻接矩阵 Floyd 预计算如果查询次数很多可以使用 Floyd-Warshall 算法在每次添加边后更新全对最短路径。javaclass Graph {private int n;private int[][] dist;public Graph(int n, int[][] edges) {this.n n;// 初始化距离矩阵dist new int[n][n];for (int i 0; i n; i) {Arrays.fill(dist[i], Integer.MAX_VALUE / 2); // 避免溢出dist[i][i] 0;}for (int[] edge : edges) {int from edge[0];int to edge[1];int cost edge[2];dist[from][to] Math.min(dist[from][to], cost);}// Floyd-Warshall 预计算floydWarshall();}private void floydWarshall() {for (int k 0; k n; k) {for (int i 0; i n; i) {for (int j 0; j n; j) {if (dist[i][k] dist[k][j] dist[i][j]) {dist[i][j] dist[i][k] dist[k][j];}}}}}public void addEdge(int[] edge) {int from edge[0];int to edge[1];int cost edge[2];// 如果新边比现有路径更短更新并重新运行 Floydif (cost dist[from][to]) {dist[from][to] cost;// 只更新受影响的路径for (int i 0; i n; i) {for (int j 0; j n; j) {if (dist[i][from] cost dist[to][j] dist[i][j]) {dist[i][j] dist[i][from] cost dist[to][j];}}}}}public int shortestPath(int node1, int node2) {return dist[node1][node2] Integer.MAX_VALUE / 2 ? -1 : dist[node1][node2];}}使用示例javapublic class Main {public static void main(String[] args) {// 初始化4个节点边列表int[][] edges {{0, 1, 1}, {1, 2, 2}, {2, 3, 3}};Graph graph new Graph(4, edges);System.out.println(graph.shortestPath(0, 3)); // 输出: 6 (0-1-2-3)System.out.println(graph.shortestPath(0, 2)); // 输出: 3 (0-1-2)// 添加新边graph.addEdge(new int[]{0, 2, 2});System.out.println(graph.shortestPath(0, 3)); // 输出: 5 (0-2-3)// 不存在路径System.out.println(graph.shortestPath(3, 0)); // 输出: -1}}复杂度分析方案一Dijkstra· 初始化O(E)· addEdgeO(1)· shortestPathO((V E) log V) O((100 100) log 100) ≈ O(200)· 适用场景查询次数少边添加频繁方案二Floyd 预计算· 初始化O(V³) O(100³) 1,000,000· addEdgeO(V²) O(10,000)· shortestPathO(1)· 适用场景查询次数非常多 1000 次关键技巧1. 使用 Integer.MAX_VALUE / 2 避免溢出防止加法运算时溢出2. Dijkstra 早期终止当弹出目标节点时立即返回提高效率3. Floyd 增量更新添加新边时只更新受影响的路径避免全量重算根据题目约束n ≤ 100最多 100 次操作两种方案都可以接受。推荐使用 Dijkstra 方案代码更简洁且不易出错。
http://www.gsyq.cn/news/1388484.html

相关文章:

  • 终极百度网盘下载速度破解指南:深度解析真实链接获取技术
  • 【技术判断力:法则一】2、架构必败根源:90%的架构活动,死在“没有唯一正确目标”
  • ARM AArch32内存管理架构与MMU实现详解
  • LVGL移植避坑指南:搞定Keil工程下的文件管理、栈溢出和屏幕撕裂(实测HC32F460)
  • 手把手教你用逻辑分析仪抓取SPI/IIC波形:从时序图到代码调试的完整实战(附Saleae使用教程)
  • 保姆级教程:在Debian 11上搞定PulseAudio 14.2与UCM2音频路由(以RK809/ES8388为例)
  • 2026年亲测有效:3种高效降论文AIGC率的方法 - 降AI实验室
  • JMeter高并发压测脚本设计范式:可伸缩、可观测、可诊断
  • 从零实现五子棋AI:极小化极大算法与Alpha-Beta剪枝实战
  • 低空经济规模化落地前置刚需:产业赛道全景+低空安防技术体系深度解析
  • Claude Code in Cursor:代理式AI编程的可审查实践
  • 一篇看懂Linux下的IIC驱动
  • Tims天好中国股权曝光:腾讯持股12% 2025年净亏4亿 资金流动性趋紧
  • 震坤行第一季营收21亿 2026目标是全年盈利
  • 2026年昭通市本地上门黄金回收门店指南 彩金+铂金+金条+白银回收门店联系方式推荐 - 大熊猫898989
  • 2026年肇庆市本地上门黄金回收门店指南 彩金+铂金+金条+白银回收门店联系方式推荐 - 大熊猫898989
  • 2026 SSH工具怎么选:多台 VPS 管理时,什么类型更省心?
  • 告别被动抢修!AI才是设备运维的正确打开方式
  • 探寻靠谱省煤器锅炉部件生产商,为你的生产节能添助力!
  • 告别串口调试烦恼:手把手教你用vTESTstudio的CAPL函数搞定VT7001通道通信
  • 华硕笔记本性能优化神器:GHelper完整使用指南与AMD降压超频技巧
  • JetBrains IDE试用重置终极指南:一键恢复30天完整功能
  • 2026年云浮市正规上门黄金白银回收品牌门店名录 K金+铂金+金条+银条回收门店联系方式推荐+指南 - 盛世金银回收
  • 氟化铈(CeF₃)特性与应用
  • 告别网络限制:手把手教你用7-Zip分卷压缩,把50G的Unreal 5.1完整搬进内网
  • 告别Transform父子关系!Unity 2022中Constraint组件的5个高效用法与避坑指南
  • AI智能体GDPR合规实战:从可观测性到强制执行记录的架构设计
  • 西门子S7-1200固件V3.0下,MODBUS TCP客户端与Modbus Slave联调全记录
  • 2026年郑州市本地上门黄金回收门店指南 彩金+铂金+金条+白银回收门店联系方式推荐 - 大熊猫898989
  • 百度网盘直链解析:5分钟实现高速下载的完整指南