[Java] 백준 12851 숨바꼭질 2

hyunnzl·2025년 2월 10일

백준

목록 보기
51/116
post-thumbnail

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

난이도

골드4

문제

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.

수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 그리고, 가장 빠른 시간으로 찾는 방법이 몇 가지 인지 구하는 프로그램을 작성하시오.

입력

첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.

출력

첫째 줄에 수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
둘째 줄에는 가장 빠른 시간으로 수빈이가 동생을 찾는 방법의 수를 출력한다.

내 코드

import java.util.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int start = Integer.parseInt(st.nextToken());
        int end = Integer.parseInt(st.nextToken());
        
        int[] visited = new int[100001];
        Arrays.fill(visited, Integer.MAX_VALUE);
        Queue<int[]> q = new LinkedList<>();
        
        int minTime = Integer.MAX_VALUE;
        int cnt = 0;

        q.add(new int[]{start, 0});
        visited[start] = 0;

        while (!q.isEmpty()) {
            int[] now = q.poll();
            int position = now[0];
            int time = now[1];

            if (time > minTime) break;

            if (position == end) {
                if (time < minTime) {
                    minTime = time;
                    cnt = 1;
                } else if (time == minTime) {
                    cnt++;
                }
            }

            int[] nextPositions = {position - 1, position + 1, position * 2};
            for (int next : nextPositions) {
                if (next >= 0 && next <= 100000) {
                    if (visited[next] >= time + 1) {
                        visited[next] = time + 1;
                        q.offer(new int[]{next, time + 1});
                    }
                }
            }
        }

        System.out.println(minTime);
        System.out.println(cnt);
    }
}

  1. visited 배열은 각 위치에 도달한 최소 시간을 기록한다.
  2. 동일한 시간이거나 더 짧은 시간에 도달하는 경우에만 큐에 추가한다.
  3. 최단 시간을 초과한 경우에는 루프를 바로 종료한다.

0개의 댓글