From bb9f1ba8a2722b153f858586712157034f81e540 Mon Sep 17 00:00:00 2001 From: Subin Kim <71137594+ksb143@users.noreply.github.com> Date: Tue, 4 Mar 2025 17:38:54 +0900 Subject: [PATCH] =?UTF-8?q?solved=20=EB=B6=80=EB=8C=80=EB=B3=B5=EA=B7=80?= =?UTF-8?q?=20-=20215.12ms=20201mb?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\352\271\200\354\210\230\353\271\210.java" | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 "Programmers/\353\266\200\353\214\200\353\263\265\352\267\200/\353\266\200\353\214\200\353\263\265\352\267\200_\352\271\200\354\210\230\353\271\210.java" diff --git "a/Programmers/\353\266\200\353\214\200\353\263\265\352\267\200/\353\266\200\353\214\200\353\263\265\352\267\200_\352\271\200\354\210\230\353\271\210.java" "b/Programmers/\353\266\200\353\214\200\353\263\265\352\267\200/\353\266\200\353\214\200\353\263\265\352\267\200_\352\271\200\354\210\230\353\271\210.java" new file mode 100644 index 0000000..b0dca18 --- /dev/null +++ "b/Programmers/\353\266\200\353\214\200\353\263\265\352\267\200/\353\266\200\353\214\200\353\263\265\352\267\200_\352\271\200\354\210\230\353\271\210.java" @@ -0,0 +1,55 @@ +package unsolved; +import java.util.*; + +public class 부대복귀_김수빈 { + public static int[] solution(int n, int[][] roads, int[] sources, int destination) { + // 인접리스트 + List> adjList = new ArrayList<>(); + for (int i = 0; i <= n; i++) { + adjList.add(new ArrayList<>()); + } + // 인접리스트 표시 + for (int[] road : roads) { + adjList.get(road[0]).add(road[1]); + adjList.get(road[1]).add(road[0]); + } + // 도착지에서 모든 노드까지 최단 거리 한번만 구하기 + int[] minDist = bfs(destination, n, adjList); + int[] answer = new int[sources.length]; + for (int i = 0; i < sources.length; i++) { + answer[i] = minDist[sources[i]]; + } + + return answer; + } + + public static int[] bfs(int d, int n, List> adjList) { + int[] dist = new int[n + 1]; + Arrays.fill(dist, -1); // 일단 모든 노드를 -1로 초기화 + Queue queue = new LinkedList<>(); + queue.offer(d); // 시작 위치 목적지로 + dist[d] = 0; // 시작 위치 0 + + while (!queue.isEmpty()) { + int curr = queue.poll(); + for (int next : adjList.get(curr)) { + // 방문하지 않았다면 + if (dist[next] == -1) { + dist[next] = dist[curr] + 1; + queue.offer(next); + } + } + } + + return dist; + } + + public static void main(String[] args) { + int[] result = solution(5, + new int[][] {{1, 2}, {1, 4}, {2, 4}, {2, 5}, {4, 5}}, + new int[] {1, 3, 5}, + 5); + + System.out.println(Arrays.toString(result)); + } +}