음 자바로 풀었습니다.

https://www.acmicpc.net/problem/13913

 

13913번: 숨바꼭질 4

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

import java.util.*;

public class Main {
    static final int MAX = 100001;  // 최대 범위 설정
    static int[] time = new int[MAX];  // 각 위치에 도달하는데 걸린 시간 저장
    static int[] path = new int[MAX];  // 이전 위치 추적

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int k = scan.nextInt();

        if (n == k) {
            System.out.println(0);
            System.out.println(n);
            return;
        }

        Arrays.fill(time, -1);  // 시간 초기화
        Queue<Integer> q = new LinkedList<>();
        q.add(n);
        time[n] = 0;
        path[n] = -1;  // 시작 위치

        while (!q.isEmpty()) {
            int current = q.poll();

            for (int next : new int[]{current - 1, current + 1, 2 * current}) {
                if (next >= 0 && next < MAX && time[next] == -1) {
                    q.add(next);
                    time[next] = time[current] + 1;
                    path[next] = current;

                    if (next == k) {
                        System.out.println(time[next]);
                        printPath(n, k);
                        return;
                    }
                }
            }
        }
    }

    private static void printPath(int start, int end) {
        if (end != start) {
            printPath(start, path[end]);
        }
        System.out.print(end + " ");
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 괄호의 값  (1) 2024.01.24
백준 톱니바퀴  (0) 2024.01.17
백준 미세먼지 안녕!  (1) 2024.01.06
백준 - 경쟁적 전염  (1) 2024.01.02
백준 치즈 2638  (1) 2023.12.19

+ Recent posts