力扣labuladong——一刷day84

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • [一、力扣743. 网络延迟时间](#一、力扣743. 网络延迟时间)

前言

Dijkstra 算法(一般音译成迪杰斯特拉算法)无非就是一个 BFS 算法的加强版,它们都是从二叉树的层序遍历衍生出来的


一、力扣743. 网络延迟时间

java 复制代码
class Solution {
    public int networkDelayTime(int[][] times, int n, int k) {
        List<int[]>[] graph = new LinkedList[n+1];
        for(int i = 1; i <= n; i ++){
            graph[i] = new LinkedList<int[]>();
        }
        for(int[] time : times){
            int from = time[0];
            int to = time[1];
            int w = time[2];
            graph[from].add(new int[]{to,w});
        }
        int[] result = dijkstra(k,graph);
        int res = 0;
        for(int i = 1; i < result.length; i ++){
            if(result[i] == Integer.MAX_VALUE){
                return -1;
            }
            res = Math.max(res,result[i]);
        }
        return res;
    }
    class State{
        int id;
        int distFromStart;
        public State(int id, int distFromStart){
            this.id = id;
            this.distFromStart = distFromStart;
        }
    }
    public int[] dijkstra(int start, List<int[]>[] graph){
        int n = graph.length;
        int[] result = new int[n];
        PriorityQueue<State> pq = new PriorityQueue<>(
            (a,b)->{
                return a.distFromStart - b.distFromStart;
            }
        );
        Arrays.fill(result,Integer.MAX_VALUE);
        result[start] = 0;
        pq.offer(new State(start,0));
        while(!pq.isEmpty()){
            State curV = pq.poll();
            int curId = curV.id;
            int curDistFromStart = curV.distFromStart;
            if(curDistFromStart > result[curId]){
                continue;
            }
            for(int[] next : graph[curId]){
                int nextId = next[0];
                int nextDist =  result[curId] + next[1];
                if(result[nextId] > nextDist){
                    result[nextId] = nextDist;
                    pq.offer(new State(nextId, result[nextId]));
                }
            }
        }
        return result;
    }
}
相关推荐
Q_970956395 分钟前
java+vue+SpringBoo校园失物招领网站(程序+数据库+报告+部署教程+答辩指导)
java·数据库·vue.js
努力写代码的熊大8 分钟前
单链表和双向链表
数据结构·链表
Wyc7240913 分钟前
Maven
java·数据库·maven
军训猫猫头15 分钟前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
程序猿小D16 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
success28 分钟前
【爆刷力扣-数组】二分查找 及 衍生题型
算法
Orlando cron1 小时前
数据结构入门:链表
数据结构·算法·链表
木头没有瓜2 小时前
idea离线安装插件
java·ide·intellij-idea
llwszx2 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
牛客企业服务2 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘