알고리즘
- 그래프 이론
- 그래프 탐색
- 너비 우선 탐색
수빈이가 동생을 찾을 수 있는 최소 시간을 구하는 문제
수빈이는 현재 위치에서 X-1, X+1, 또는 2*X로 이동할 수 있으며, 각 이동은 1초의 시간이 소요

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String[] inputs = input.split(" ");
N = Integer.valueOf(inputs[0]);
K = Integer.valueOf(inputs[1]);
private static int bfs(int node)
{
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(node);
int index = node;
int n = 0;
visited[index] = 1;
while (queue.isEmpty() == false)
{
n = queue.remove();
if (n == K)
{
return visited[n]-1;
}
if (n-1>=0 && visited[n-1] == 0)
{
visited[n-1] = visited[n]+1;
queue.add(n-1);
}
if (n+1 <= 100000 && visited[n+1] == 0)
{
visited[n+1] = visited[n]+1;
queue.add(n+1);
}
if (2*n <= 100000 && visited[2*n] == 0)
{
visited[2*n] = visited[n] + 1;
queue.add(2*n);
}
}
return -1;
}
int result = bfs(N);
System.out.println(result);
import java.io.*;
import java.util.*;
public class Main
{
static int N;
static int K;
static int visited[] = new int[100001];
// X-1, X+1
// 2*X
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String[] inputs = input.split(" ");
N = Integer.valueOf(inputs[0]);
K = Integer.valueOf(inputs[1]);
int result = bfs(N);
System.out.println(result);
}
private static int bfs(int node)
{
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(node);
int index = node;
int n = 0;
visited[index] = 1;
while (queue.isEmpty() == false)
{
n = queue.remove();
if (n == K)
{
return visited[n]-1;
}
if (n-1>=0 && visited[n-1] == 0)
{
visited[n-1] = visited[n]+1;
queue.add(n-1);
}
if (n+1 <= 100000 && visited[n+1] == 0)
{
visited[n+1] = visited[n]+1;
queue.add(n+1);
}
if (2*n <= 100000 && visited[2*n] == 0)
{
visited[2*n] = visited[n] + 1;
queue.add(2*n);
}
}
return -1;
}
}