
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int N;
static int K;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
bw.write(bfs() + "\n");
bw.close();
}
private static int bfs() {
Queue<int[]> queue = new LinkedList<>();
boolean[] visited = new boolean[100001];
int result = 0;
queue.add(new int[]{N, 0});
visited[N] = true;
while (!queue.isEmpty()) {
int[] current = queue.poll();
if (current[0] == K) {
result = current[1];
break;
}
int[] next = {current[0] - 1, current[0] + 1, current[0] * 2};
for (int temp : next) {
if (temp >= 0 && temp <= 100000 && !visited[temp]) {
visited[temp] = true;
queue.add(new int[]{temp, current[1] + 1});
}
}
}
return result;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 1074번: Z (0) | 2025.03.25 |
|---|---|
| [JAVA-자바] 14940번: 쉬운 최단거리 (0) | 2025.03.25 |
| [JAVA-자바] 18870번: 좌표 압축 (0) | 2025.03.21 |
| [JAVA-자바] 11724번: 연결 요소의 개수 (0) | 2025.03.21 |
| [JAVA-자바] 2805번: 나무 자르기 (0) | 2025.03.21 |