문제
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
출력
수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
예제 입력 1
5 17
예제 출력 1
4
수빈이의 위치에서 시작하여 찾으러 갈 수 있는 방법들을 모두 본 후,
해당 위치에 도달하는데 걸리는 시간을 board 배열에 작성한다.
동생의 위치에 도달한다면 동생 위치의 board 시간을 보면 된다.
가장 빨리 동생에게 도달하는 시간을 구해야하므로 BFS를 사용하여 풀었다.
풀이 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class 숨바꼭질_1697 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] board = new int[100001];
board[n] = 1;
Queue<Integer> queue1 = new LinkedList<>();
queue1.offer(n);
int time = 0;
while (!queue1.isEmpty()) {
int current = queue1.poll();
if (current == k) {
pw.println(board[current]-1);
}
if (current - 1 >= 0 && board[current - 1] == 0) {
board[current - 1] = board[current]+1;
queue1.offer(current - 1);
}
if (current + 1 <= 100000 && board[current + 1] == 0) {
board[current + 1] = board[current]+1;
queue1.offer(current + 1);
}
if (current * 2 <= 100000 && board[current * 2] == 0) {
board[current * 2] = board[current]+1;
queue1.offer(current * 2);
}
}
br.close();
pw.close();
}
}
'알고리즘 > 백준' 카테고리의 다른 글
| [백준] 제출 25757 (0) | 2026.02.13 |
|---|---|
| [백준]촌수계산 2644 (1) | 2024.01.04 |
| [백준]좋다 1253 (0) | 2023.12.13 |
| [백준] 배열돌리기4 17406 (1) | 2023.12.07 |
| [백준]감시 15683 (2) | 2023.12.06 |