JuSeok

1697번

문제

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

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

문제 해결 순서

  1. 너비우선탐색 문제이므로 큐를 이용해 구현.
  2. +1, -1, *2, 3가지 경우를 차례대로 큐에 삽입.
  3. 배열 arr에 몇 초가 걸렸는지 저장.
  4. 하나씩 큐에서 빼며 동생의 위치인지 검사.
  5. 큐에서 뺀 값이 동생의 위치와 같다면 배열 arr의 동생 번째를 출력.
import java.util.*;
public class Main {

    static int N;
    static int K;
    static int arr[] = new int[100001];
    static boolean visit[] = new boolean[100001];
    static Queue<Integer> queue = new LinkedList<>();
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        N = scan.nextInt();
        K = scan.nextInt();
        queue.add(N);
        arr[N] = 0;
        bfs();
    }

    static void bfs(){
        // +1, -1, *2
        while(!queue.isEmpty()){
            int temp = queue.poll();
            if(temp == K){
                System.out.println(arr[K]);
                return;
            }
            // + 1 인 경우
            if(temp + 1 <= 100000 && !visit[temp + 1]){
                visit[temp + 1] = true;
                arr[temp + 1] = arr[temp] + 1;
                queue.add(temp + 1);
            }
            // - 1 인 경우
            if(temp - 1 >= 0 && !visit[temp - 1]){
                visit[temp - 1] = true;
                queue.add(temp - 1);
                arr[temp - 1] = arr[temp] + 1;
            }
            // * 2 인 경우
            if(temp * 2 <= 100000 && !visit[temp * 2]){
                visit[temp * 2] = true;
                queue.add(temp * 2);
                arr[temp * 2] = arr[temp] + 1;
            }
        }
    }
}

Tags