forked from ndb796/Fast_Campus_Algorithm_Lecture_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path[14]_2.java
46 lines (39 loc) · 968 Bytes
/
[14]_2.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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static int MAX = 100001;
public static int n, k;
public static int[] data = new int[MAX];
// 너비 우선 탐색(BFS)
public static int bfs() {
Queue<Integer> q = new LinkedList<Integer>();
q.offer(n);
while (!q.isEmpty()) {
int now = q.poll();
if (now == k) return data[now];
int next = now - 1;
if (0 <= next && next < MAX && data[next] == 0) {
data[next] = data[now] + 1;
q.add(next);
}
next = now + 1;
if (0 <= next && next < MAX && data[next] == 0) {
data[next] = data[now] + 1;
q.add(next);
}
next = now * 2;
if (0 <= next && next < MAX && data[next] == 0) {
data[next] = data[now] + 1;
q.add(next);
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
System.out.println(bfs());
}
}