Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Seol-JY/202506/12 BOJ G5 숨바꼭질 3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
```java
import java.io.*;
import java.util.*;

public class Main {
static int N, K;
static int[] dist = new int[100001];
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());

Arrays.fill(dist, Integer.MAX_VALUE);

System.out.println(bfs());
}

static int bfs() {
Deque<Integer> deque = new ArrayDeque<>();
deque.offer(N);
dist[N] = 0;

while (!deque.isEmpty()) {
int current = deque.poll();

if (current == K) {
return dist[current];
}

if (visited[current]) continue;
visited[current] = true;

if (current * 2 <= 100000 && dist[current * 2] > dist[current]) {
dist[current * 2] = dist[current];
deque.offerFirst(current * 2);
}

if (current - 1 >= 0 && dist[current - 1] > dist[current] + 1) {
dist[current - 1] = dist[current] + 1;
deque.offerLast(current - 1);
}

if (current + 1 <= 100000 && dist[current + 1] > dist[current] + 1) {
dist[current + 1] = dist[current] + 1;
deque.offerLast(current + 1);
}
}

return dist[K];
}
}
```