-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
49 lines (41 loc) · 1.19 KB
/
Main.java
File metadata and controls
49 lines (41 loc) · 1.19 KB
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
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[] cnt;
static boolean[] visited;
static Queue<Integer> q;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
cnt = new int[100001];
Arrays.fill(cnt, 0);
visited = new boolean[100001];
Arrays.fill(visited, Boolean.FALSE);
q = new LinkedList<Integer>();
int answer = bfs(N, K);
System.out.println(answer);
sc.close();
}
public static int bfs(int n, int k){
q.add(n);
visited[n] = true;
while(!q.isEmpty()){
int pos = q.poll();
if (pos == k) {
return cnt[pos];
}
int[] rules = {pos-1, pos+1, pos*2};
for(int nextPos : rules){
if(0 <= nextPos && nextPos < 100001 && !visited[nextPos]){
cnt[nextPos] = cnt[pos] + 1;
visited[nextPos] = true;
q.add(nextPos);
}
}
}
return -1;
}
}