From eda52c1202c22e7ba9546cc049db267c74b7c0b2 Mon Sep 17 00:00:00 2001 From: Ukj0ng <90972240+Ukj0ng@users.noreply.github.com> Date: Fri, 26 Sep 2025 21:19:46 +0900 Subject: [PATCH] =?UTF-8?q?[20250926]=20PGM=20/=20LV3=20/=20=EB=B6=80?= =?UTF-8?q?=EB=8C=80=EB=B3=B5=EA=B7=80=20/=20=ED=95=9C=EC=A2=85=EC=9A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...00\353\214\200\353\263\265\352\267\200.md" | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 "Ukj0ng/202509/26 PGM LV3 \353\266\200\353\214\200\353\263\265\352\267\200.md" diff --git "a/Ukj0ng/202509/26 PGM LV3 \353\266\200\353\214\200\353\263\265\352\267\200.md" "b/Ukj0ng/202509/26 PGM LV3 \353\266\200\353\214\200\353\263\265\352\267\200.md" new file mode 100644 index 00000000..ad9076f4 --- /dev/null +++ "b/Ukj0ng/202509/26 PGM LV3 \353\266\200\353\214\200\353\263\265\352\267\200.md" @@ -0,0 +1,70 @@ +``` +import java.util.*; + +class Solution { + private final int INF = Integer.MAX_VALUE - 10; + private List[] graph; + private int[] dist; + + public int[] solution(int n, int[][] roads, int[] sources, int destination) { + init(n, roads); + int[] answer = new int[sources.length]; + + dijkstra(destination); + + for (int i = 0; i < answer.length; i++) { + int result = dist[sources[i]]; + if (result == INF) answer[i] = -1; + else answer[i] = result; + } + + return answer; + } + + private void init(int n, int[][] roads) { + graph = new List[n+1]; + dist = new int[n+1]; + + for (int i = 0; i <= n; i++) { + graph[i] = new ArrayList<>(); + } + + for (int[] road : roads) { + graph[road[0]].add(road[1]); + graph[road[1]].add(road[0]); + } + } + + private void dijkstra(int start) { + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1.cost, o2.cost)); + Arrays.fill(dist, INF); + dist[start] = 0; + pq.add(new Node(start, dist[start])); + + while (!pq.isEmpty()) { + Node current = pq.poll(); + + if (current.cost > dist[current.dest]) continue; + + for (Integer next : graph[current.dest]) { + int nCost = 1 + dist[current.dest]; + + if (nCost < dist[next]) { + dist[next] = nCost; + pq.add(new Node(next, dist[next])); + } + } + } + } + + class Node { + int dest; + int cost; + + Node (int dest, int cost) { + this.dest = dest; + this.cost = cost; + } + } +} +```