문제 링크

분류

0-1 너비 우선 탐색, 너비 우선 탐색, 데이크스트라, 그래프 이론, 그래프 탐색

 

문제 설명

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

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

 

입력

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

 

출력

수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.

 

풀이 (BFS)

시간 복잡도 O(N) 공간 복잡도 O(N) N: 1000001 (배열의 최대 길이)

아이디어: 기존의 숨바꼭질 문제에서 텔레포트 하는 로직의 시간이 0이 되기 때문에 한 사이클에서 한 번만 동작하는게 아닌 배열의 최대 길이의 근접 할 때까지 현재 위치에서 텔레포트를 함을 처리하고 한칸 뒤로 한칸 앞으로 가는 로직을 처리해야 한다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());
        if(N==K){
            System.out.println(0);
            return;
        }
        int[] map = new int[100001];
        Arrays.fill(map,-1);
        Queue<ArrayList<int[]>> queue = new LinkedList<>();
        ArrayList<int[]> node = new ArrayList<>();
        node.add(new int[]{N,0});
        map[N] = 0;
        queue.add(node);
        while(!queue.isEmpty()){
            ArrayList<int[]> cur = queue.poll();
            ArrayList<int[]> nextNode = new ArrayList<>();
            for (int[] ints : cur) {
                int time = 1+ints[1];
                int pos = ints[0];
                int tmp = pos;
                while(tmp*2<=100000&&map[tmp*2]==-1){
                    tmp*=2;
                    map[tmp] = time-1;
                    nextNode.add(new int[]{tmp,time-1});
                }
                if(pos-1>=0&&map[pos-1]==-1) {
                    map[pos-1] = time;
                    nextNode.add(new int[]{pos-1,time});
                }
                if(pos+1<=100000&&map[pos+1]==-1) {
                    map[pos+1] = time;
                    nextNode.add(new int[]{pos+1,time});
                }

                if(pos-1==K||pos+1==K||tmp==K){
                    System.out.println(map[K]);
                    return;
                }
            }
            queue.add(nextNode);
        }
        System.out.println(-1);
    }
}

 

'PS > Gold' 카테고리의 다른 글

[Gold IV] 치즈 - 2636 (Java)  (0) 2023.08.20
[Gold V] 공주님을 구해라! - 17836 (Java)  (0) 2023.08.17
[Gold V] 토마토 - 7569 (Java)  (0) 2023.08.15
[Gold IV] 숨바꼭질 4 - 13913 (Java)  (0) 2023.08.04
[Gold V] 토마토 - 7576 (Java)  (0) 2023.08.02

+ Recent posts