본문 바로가기
Coding Test/백준 알고리즘 풀이

[백준] 13549 숨바꼭질3 (자바) : BFS

by CSEGR 2024. 7. 9.
728x90

문제

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

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

입력

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

출력

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

예제 입력 1 복사

5 17

예제 출력 1 복사

2

힌트

수빈이가 5-10-9-18-17 순으로 가면 2초만에 동생을 찾을 수 있다.

 

 

문제 설명

노드에 도착할 때마다 시간을 함께 Queue에 기록한다. 

 

5 -> 10 -> 4 -> 6 -> 20 -> 9 -> 11 -> 8 -> 3 -> 12 -> 7 -> 40 -> 19 -> 21 -> 18 -> 8 -> 10 -> 22 -> 10 -> 12 -> 16 -> ...

 

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;



public class Main{
    static int subin, sister;
    static boolean[] visited= new boolean[100001];
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        subin = Integer.parseInt(st.nextToken());
        sister = Integer.parseInt(st.nextToken());

        search(subin);
    }
    public static void search(int subin){
        Queue<Point> q = new LinkedList<>();

        q.add(new Point(subin, 0));

        while(!q.isEmpty()){
            Point current = q.poll();
            int current_location = current.x;
            int current_time = current.y;

            visited[current_location] = true;

            if(current_location == sister){
                System.out.println(current_time);
                return;
            }

            if(current_location *2 <= 100000 && !visited[2*current_location]){
                q.add(new Point(2*current_location, current_time));
            }
            if(current_location-1 >= 0 && !visited[current_location-1]){
                q.add(new Point(current_location-1, current_time+1));
            }
            if(current_location+1 <= 100000 && !visited[current_location+1]){
                q.add(new Point(current_location+1, current_time+1));
            }
        }


    }
}

 

728x90