File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int N , K ;
7+ static int [] dist = new int [100001 ];
8+ static boolean [] visited = new boolean [100001 ];
9+
10+ public static void main (String [] args ) throws IOException {
11+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
12+ StringTokenizer st = new StringTokenizer (br. readLine());
13+
14+ N = Integer . parseInt(st. nextToken());
15+ K = Integer . parseInt(st. nextToken());
16+
17+ Arrays . fill(dist, Integer . MAX_VALUE );
18+
19+ System . out. println(bfs());
20+ }
21+
22+ static int bfs () {
23+ Deque<Integer > deque = new ArrayDeque<> ();
24+ deque. offer(N );
25+ dist[N ] = 0 ;
26+
27+ while (! deque. isEmpty()) {
28+ int current = deque. poll();
29+
30+ if (current == K ) {
31+ return dist[current];
32+ }
33+
34+ if (visited[current]) continue ;
35+ visited[current] = true ;
36+
37+ if (current * 2 <= 100000 && dist[current * 2 ] > dist[current]) {
38+ dist[current * 2 ] = dist[current];
39+ deque. offerFirst(current * 2 );
40+ }
41+
42+ if (current - 1 >= 0 && dist[current - 1 ] > dist[current] + 1 ) {
43+ dist[current - 1 ] = dist[current] + 1 ;
44+ deque. offerLast(current - 1 );
45+ }
46+
47+ if (current + 1 <= 100000 && dist[current + 1 ] > dist[current] + 1 ) {
48+ dist[current + 1 ] = dist[current] + 1 ;
49+ deque. offerLast(current + 1 );
50+ }
51+ }
52+
53+ return dist[K ];
54+ }
55+ }
56+ ```
You can’t perform that action at this time.
0 commit comments