문제
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
출력
수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
예제
BFS
import java.io.*;
import java.util.*;
public class Main {
static int N, K;
static Queue<int[]> que = new LinkedList<>();
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(), " ");
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
System.out.println(bfs(N,K));
}
public static int bfs(int start, int end){
int depth = 0;
que.offer(new int[]{start,depth});
visited[start] = true;
while(!que.isEmpty()){
int idx[] = que.poll();
int curr_idx = idx[0];
int curr_depth = idx[1];
if(idx[0] == end){
depth = curr_depth;
break;
} else {
curr_depth++;
if(is_vaild_range(curr_idx+1)){
if(!visited[curr_idx+1]){
visited[curr_idx+1] = true;
que.offer(new int[]{curr_idx+1,curr_depth});
}
}
if(is_vaild_range(curr_idx-1)){
if(!visited[curr_idx-1]){
visited[curr_idx-1] = true;
que.offer(new int[]{curr_idx-1,curr_depth});
}
}
if(is_vaild_range(curr_idx*2)){
if(!visited[curr_idx*2])
{
visited[curr_idx*2] = true;
que.offer(new int[]{curr_idx*2,curr_depth});
}
}
}
}
return depth;
}
static boolean is_vaild_range(int idx){
return (idx >= 0 && idx <= 100000);
}
}
[백준] 2583 영역 구하기 (JAVA) (0) | 2023.07.28 |
---|---|
[백준] 2667 단지번호붙이기 / 그래프 탐색 - DFS, BFS (0) | 2023.07.28 |
[백준] 1743 음식물 피하기 / 그래프 탐색 - DFS, BFS (0) | 2023.07.28 |
[백준] 1182 부분수열의 합 (JAVA) (0) | 2023.07.27 |
댓글,
ella_travel