-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP048_BJ1697_숨바꼭질.java
55 lines (42 loc) · 1.15 KB
/
P048_BJ1697_숨바꼭질.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
// bfs
public class P048_BJ1697_숨바꼭질 {
static int K;
static boolean[] visited = new boolean[100001];
static void bfs(int start) {
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[] {start, 0});
visited[start] = false;
while (!q.isEmpty()) {
int[] current = q.poll();
if (current[0] == K) {
System.out.println(current[1]);
return;
}
// - 1
if (current[0] - 1 >= 0 && !visited[current[0] - 1]) {
q.offer(new int[] {current[0] - 1, current[1] + 1});
visited[current[0] - 1] = true;
}
// + 1
if (current[0] + 1 < 100001 && !visited[current[0] + 1]) {
q.offer(new int[] {current[0] + 1, current[1] + 1});
visited[current[0] + 1] = true;
}
// * 2
if (current[0] * 2 < 100001 && !visited[current[0] * 2]) {
q.offer(new int[] {current[0] * 2, current[1] + 1});
visited[current[0] * 2] = true;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
K = sc.nextInt();
if (N == K) System.out.println(0);
else bfs(N);
}
}