日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode743. 网络延迟时间(迪杰斯特拉算法)

發(fā)布時(shí)間:2023/11/29 编程问答 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode743. 网络延迟时间(迪杰斯特拉算法) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

有 N 個(gè)網(wǎng)絡(luò)節(jié)點(diǎn),標(biāo)記為 1 到 N。

給定一個(gè)列表 times,表示信號(hào)經(jīng)過有向邊的傳遞時(shí)間。 times[i] = (u, v, w),其中 u 是源節(jié)點(diǎn),v 是目標(biāo)節(jié)點(diǎn), w 是一個(gè)信號(hào)從源節(jié)點(diǎn)傳遞到目標(biāo)節(jié)點(diǎn)的時(shí)間。
現(xiàn)在,我們從某個(gè)節(jié)點(diǎn) K 發(fā)出一個(gè)信號(hào)。需要多久才能使所有節(jié)點(diǎn)都收到信號(hào)?如果不能使所有節(jié)點(diǎn)收到信號(hào),返回 -1。

示例:

輸入:times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
輸出:2

代碼

class Solution {HashMap<Integer, List<int[]>> map;HashMap<Integer,Integer> dist;public int networkDelayTime(int[][] times, int N, int K) {dist=new HashMap<>();map=new HashMap<>();boolean[] check=new boolean[N+1];for(int[] time:times)//構(gòu)造鄰接表{ if(!map.containsKey(time[0]))map.put(time[0], new ArrayList<int[]>());map.get(time[0]).add(new int[]{time[1],time[2]});}for(int i=1;i<=N;i++)dist.put(i,Integer.MAX_VALUE); dist.put(K,0);while (true){int curDist=Integer.MAX_VALUE;int curNode=-1;for(int i=1;i<=N;i++)if(!check[i]&&dist.get(i)<curDist)//找出當(dāng)前距離起點(diǎn)的最近的節(jié)點(diǎn){curDist=dist.get(i);curNode=i;}if(curNode<0) break;//遍歷完了所有節(jié)點(diǎn)check[curNode]=true;//當(dāng)前節(jié)點(diǎn)已經(jīng)被訪問if(map.containsKey(curNode)){for(int[] next:map.get(curNode))//更新鄰接點(diǎn)與起點(diǎn)的最小距離dist.put(next[0], Math.min(next[1]+dist.get(curNode),dist.get(next[0])));}}int cnt=0;for(int c:dist.values())//遍歷所有的節(jié)點(diǎn)到起點(diǎn)的距離{ if(c==Integer.MAX_VALUE) return -1;cnt= Math.max(c,cnt);}return cnt;} }

堆實(shí)現(xiàn)代碼

HashMap<Integer, List<int[]>> map;public int networkDelayTime(int[][] times, int N, int K) {HashMap<Integer,Integer> dist=new HashMap<>();map=new HashMap<>();boolean[] check=new boolean[N+1];for(int[] time:times)//構(gòu)造鄰接表{ if(!map.containsKey(time[0]))map.put(time[0], new ArrayList<int[]>());map.get(time[0]).add(new int[]{time[1],time[2]});}PriorityQueue<int[]> priorityQueue=new PriorityQueue<>(((o1, o2) -> o1[0]-o2[0]));//按距離從小到大priorityQueue.offer(new int[]{0,K});//將起點(diǎn)加入優(yōu)先隊(duì)列while (!priorityQueue.isEmpty()){int[] temp=priorityQueue.poll();int d=temp[0],node=temp[1];if(dist.containsKey(node)) continue;//已經(jīng)確定了距離的不再訪問dist.put(node,d);if(map.containsKey(node))for(int[] next:map.get(node))//將鄰接點(diǎn)到起點(diǎn)的距離加入優(yōu)先隊(duì)列{ if(!dist.containsKey(next[0]));{priorityQueue.offer(new int[]{d+next[1],next[0]});}}}if(dist.size()!=N) return -1;int cnt=0;for(int c:dist.values()){cnt= Math.max(c,cnt);}return cnt;}

總結(jié)

以上是生活随笔為你收集整理的leetcode743. 网络延迟时间(迪杰斯特拉算法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。