1. 程式人生 > 實用技巧 >LeetCode 圖篇

LeetCode 圖篇

743. 網路延遲時間

有 N 個網路節點,標記為 1 到 N。

給定一個列表 times,表示訊號經過有向邊的傳遞時間。 times[i] = (u, v, w),其中 u 是源節點,v 是目標節點, w 是一個訊號從源節點傳遞到目標節點的時間。

現在,我們從某個節點 K 發出一個訊號。需要多久才能使所有節點都收到訊號?如果不能使所有節點收到訊號,返回 -1。

示例:

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

注意:

N 的範圍在 [1, 100] 之間。
K 的範圍在 [1, N] 之間。
times 的長度在 [1, 6000] 之間。
所有的邊 times[i] = (u, v, w) 都有 1 <= u, v <= N 且 0 <= w <= 100。

solution 1(Dijkstra演算法)

    public int networkDelayTime(int[][] times, int N, int K) {
        //整理圖為散列表
        Map<Integer,List<int[]>> graph = new HashMap();
        for(int[] row:times){
            if (!graph.containsKey(row[0])) {
                graph.put(row[0],new ArrayList<int[]>());
            }
            graph.get(row[0]).add(new int[]{row[1],row[2]});
        }
        //初始化儲存起點到每一個的距離的陣列 和 已遍歷點的儲存
        int[] dist = new int[N+1];
        boolean[] isread = new boolean[N+1];
        Arrays.fill(dist,0x3f3f3f3f);
        dist[0] = K; dist[K] = 0;
        //用最小堆對要處理的點進行排序
        PriorityQueue<Integer> queue = new PriorityQueue<>(
                (point1,point2) -> dist[point1] - dist[point2]);
        queue.offer(K);
        //遍歷 處理每一個點,修改到每一個點的最小距離
        while(!queue.isEmpty()){
            Integer curr = queue.poll();
            if (isread[curr]) continue;
            isread[curr] = true;
            //遍歷處理點的邊到的第二個點
            List<int[]> list = graph.getOrDefault(curr, Collections.emptyList());
            for(int[] currEdge: list){
                int next = currEdge[0];
                if(isread[next]) continue;
                dist[next] = Math.min(dist[next],dist[curr]+currEdge[1]);
                queue.offer(next);
            }
        }
        //遍歷距離陣列取結果
        int max = Arrays.stream(dist).max().getAsInt();
        return max == 0x3f3f3f3f ? -1: max;
    }
}