https://leetcode.com/problems/network-delay-time/description/
import java.util.*;
class Solution {
static class Edge {
private int to, distance;
public Edge(int to, int distance) {
this.to = to;
this.distance = distance;
}
}
static class Entry implements Comparable<Entry> {
private int node, distance;
public Entry(int node, int distance) {
this.node = node;
this.distance = distance;
}
@Override
public int compareTo(Entry o) {
return this.distance - o.distance;
}
}
public int networkDelayTime(int[][] times, int n, int k) {
Map<Integer, List<Edge>> graph = new HashMap<>();
for (int[] time : times) {
// 출발 노드가 그래프에 없으면 빈 ArrayList를 추가
graph.putIfAbsent(time[0], new ArrayList<>());
// 출발 노드의 간선 리스트에 새로운 Edge를 추가
graph.get(time[0]).add(new Edge(time[1], time[2]));
}
final int INF = Integer.MAX_VALUE;
int[] distance = new int[n + 1];
Arrays.fill(distance, INF);
Queue<Entry> pq = new PriorityQueue<>();
pq.add(new Entry(k, 0));
distance[k] = 0;
while (!pq.isEmpty()) {
Entry current = pq.remove();
if (distance[current.node] < current.distance)
continue;
// graph.containsKey : 특정 키가 맵에 존재하는지 확인
if (graph.containsKey(current.node)) {
for (Edge edge : graph.get(current.node)) {
int newDist = current.distance + edge.distance;
if (newDist < distance[edge.to]) {
distance[edge.to] = newDist;
pq.add(new Entry(edge.to, newDist));
}
}
}
}
int maxTime = 0;
for(int i = 1; i <= n; i++){
if(distance[i] == INF) return -1; // 도달할 수 없는 노드가 있는 경우
maxTime = Math.max(maxTime, distance[i]); // 최대 시간 : 가장 먼 노드까지 걸린 시간 = 모든 네트워크에 신호 전달
}
return maxTime;
}
}
for (int i = 0; i < times.length; i++) {
graph.put(times[i][0], List.of(new Edge(times[i][1], times[i][2])));
}
<처음 그래프 초기화시 위의 코드가 되지 않는 이유>
List.of(new Edge(times[i][1], times[i][2]))를 사용하여 불변(immutable) 리스트를 생성예를 들어
times 배열이 [[1, 2, 4], [1, 3, 2], [2, 3, 5]]인 경우, 그래프의 초기화 과정에서 graph.put(1, List.of(new Edge(2, 4)))로 인해 출발 노드 1의 간선 리스트는 [Edge(2, 4)]로 초기화graph.put(1, List.of(new Edge(3, 2)))로 인해, 출발 노드 1의 간선 리스트는 [Edge(3, 2)]로 덮어쓰여지게 됨Edge(2, 4)와 Edge(3, 2)가 아닌 Edge(3, 2)만 남게 됨