Network Delay Time(https://leetcode.com/problems/network-delay-time)
문제 설명
You are given a network of
nnodes, labeled from1ton. You are also giventimes, a list of travel times as directed edges times[i] = (, , ), where is the source node, is the target node, and is the time it takes for a signal to travel from source to target.We will send a signal from a given node
k. Return the minimum time it takes for all thennodes to receive the signal. If it is impossible for all thennodes to receive the signal, return-1.문제 해석
- 1~n개의 노드로 구성된 네트워크가 제공된다.
- [출발 노드 번호, 도착 노드 번호, 걸리는 시간]이 저장된 2차원 배열 times도 제공된다.
- 노드 k에서 신호를 보낼 때, 모든 노드에 신호가 도달하는 최소 시간을 반환하라. 만약 모든 노드에 신호가 도달하는 것이 불가능하면 -1을 반환하라.
제한사항
- 1 <= k <= n <= 100
- 1 <= times.length <= 6000
- times[i].length == 3
- 1 <= ui, vi <= n
- ui != vi
- 0 <= wi <= 100
- All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
입출력 예
Example 1:
- Input: times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, k = 2
- Output: 2
Example 2:
- Input: times = [[1, 2, 1]], n = 2, k = 1
- Output: 1
Example 3:
- Input: times = [[1, 2, 1]], n = 2, k = 2
- Output: -1
import java.util.*;
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int i = 1; i <= n; i++) {
graph.put(i, new ArrayList<>());
}
for(int[] time : times) {
// u -> v 로 가는 경로와 가중치 w를 그래프에 추가
graph.get(time[0]).add(new int[]{time[1], time[2]});
}
return dijkstra(graph, k, n);
}
private int dijkstra(Map<Integer, List<int[]>> graph, int start, int n) {
int[] distance = new int[n + 1];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[start] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparing(a -> a[1]));
pq.add(new int[]{start, 0});
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int node = cur[0];
int time = cur[1];
if (time > distance[node]) continue;
// 인접 노드 확인
for (int[] edge : graph.get(node)) {
int nextNode = edge[0];
int nextTime = time + edge[1];
if (nextTime < distance[nextNode]) {
distance[nextNode] = nextTime;
pq.add(new int[]{nextNode, nextTime});
}
}
}
return find(distance, n);
}
private int find(int[] distance, int n) {
int maxTime = 0;
for (int i = 1; i <= n; i++) {
if (distance[i] == Integer.MAX_VALUE) {
return -1;
}
maxTime = Math.max(maxTime, distance[i]);
}
return maxTime;
}
}