import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
//TIP 코드를 <b>실행</b>하려면 <shortcut actionId="Run"/>을(를) 누르거나
// 에디터 여백에 있는 <icon src="AllIcons.Actions.Execute"/> 아이콘을 클릭하세요.
public class Main {
public static int N, K, ans;
public static int[] visited = new int[100001];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
// 1. 입력받기
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
ans = 0;
// 2. bfs 탐색
ans = bfs();
// 3. 출력하기
System.out.println(ans);
}
public static int bfs() {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{N, 0});
visited[N] = 1;
while (!q.isEmpty()) {
int[] cur = q.poll();
int x = cur[0];
int dis = cur[1];
if (x == K) {
return dis;
}
if (x + 1 <= 100000 && visited[x + 1] == 0) {
visited[x + 1] = 1;
q.add(new int[]{x + 1, dis + 1});
}
if (x - 1 >= 0 && visited[x - 1] == 0) {
visited[x - 1] = 1;
q.add(new int[]{x - 1, dis + 1});
}
if (2 * x <= 100000 && visited[2 * x] == 0) {
visited[2 * x] = 1;
q.add(new int[]{2 * x, dis + 1});
}
}
return 0;
}
}
풀이 사항
풀이 일자: 2024.01..06
풀이 시간: 50분
채점 결과: 정답
예상 문제 유형: bfs
시간: 132ms
메모리: 19216KB
풀이방법
- N, K를 입력받은 후 100001까지 방문 배열을 만든다.
- int배열을 받을 수 있는 큐를 만든다음 N, 0 부터 큐에 넣어준다. 첫번째 값은 현재 위치 두번째 값은 걸린 시간을 의미한다.
- K에 도착한다면 현재 시간을 반환해준 뒤 바로 빠져나오고 이외의 경우에는 방문을 체크해 주고 범위를 넘어가지 않는다면 -1, +1, *2를 해준값과 시간 + 1 해서 다음 큐에 넣어준다.
'코딩테스트 > JAVA' 카테고리의 다른 글
[백준 JAVA] 1012번: 유기농 배추 (0) | 2025.01.06 |
---|---|
[SWEA] 1824번: 혁진이의 프로그램 검증 (1) | 2024.11.15 |
[백준 JAVA] 18809번: Gaaaaaaaaaarden (0) | 2024.11.06 |
[프로그래머스 JAVA] 지형 이동 (0) | 2024.10.30 |
[백준 JAVA] 18429번: 근손실 (0) | 2024.10.25 |