力扣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;
    }
}
相关推荐
与火星的孩子对话5 分钟前
Unity高级开发:反射原理深入解析与实践指南 C#
java·unity·c#·游戏引擎·lucene·反射
1白天的黑夜120 分钟前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
花火|24 分钟前
算法训练营day55 图论⑤ 并查集理论基础、107. 寻找存在的路径
算法·图论
花火|25 分钟前
算法训练营day56 图论⑥ 108. 109.冗余连接系列
算法·图论
上海迪士尼3526 分钟前
力扣子集问题C++代码
c++·算法·leetcode
花开富贵ii26 分钟前
代码随想录算法训练营四十六天|图论part04
java·数据结构·算法·图论
SunnyKriSmile28 分钟前
【冒泡排序】
c语言·算法·排序算法
熬了夜的程序员29 分钟前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
小亮✿30 分钟前
算法——快速幂
算法