๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 1697 - ์ˆจ๋ฐ”๊ผญ์งˆ

by applemango2021 2020. 12. 12.

๋‚œ BFS๋กœ ํ’€์—ˆ๋Š”๋ฐ, ์‚ฌ์‹ค DFS๊ฐ€ ๋” ๋น ๋ฅผ ์ˆ˜ ๋ฐ–์— ์—†์„ ๊ฒƒ ๊ฐ™๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋„˜ ์‰ฝ๊ฒŒ ํ’€์–ด์„œ ๋ถ„๋ช… ๋‚œ์ด๋„๊ฐ€ ๋†’์•„์ง€๋Š” ์‹œ๋ฆฌ์ฆˆ ๋ฌธ์ œ๋“ค์ด ์žˆ์„ ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ์ง„์งœ ์žˆ๋‹ค. ์–ผํ• ๋ดค์„ ๋•Œ์—๋Š” ์ˆจ๋ฐ”๊ผญ์งˆ 4๊นŒ์ง€๋Š” N, K ๋ฒ”์œ„๋„ ๋˜‘๊ฐ™๊ณ  ๋ฌธ์ œ๋„ ๊ฑฐ์˜ ์œ ์‚ฌํ•œ ๊ฒƒ ๊ฐ™์€๋ฐ ๋‚œ์ด๋„๊ฐ€ ์ฐจ์ด๋‚˜์„œ ๋ญ์ง€ ์‹ถ๋‹ค. ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ ์ฐจ์ด์ธ๊ฐ€?

/* 2020.12.12(ํ† )*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] str = br.readLine().trim().split(" ");
		int N = Integer.parseInt(str[0]);
		int K = Integer.parseInt(str[1]);
		
		boolean[] visited = new boolean[100001];
		Queue<int[]> que = new LinkedList<int[]>();
		que.offer(new int[] {N,0});
		
		int cnt = 0;
		int currPos;
		
		int[] tmp;
		int nextPos;
		while(!que.isEmpty()) {
			tmp = que.poll();
			currPos = tmp[0];
			cnt = tmp[1];
			
			//๋„์ฐฉํ•œ ๊ณณ์ด ๋™์ƒ์˜ ์œ„์น˜๋ฉด break;
			if(currPos == K) break;
			
			visited[currPos] = true;
			
			nextPos = currPos * 2;
			if(nextPos>=0 && nextPos<=100000 && !visited[nextPos] ) 
            	que.offer(new int[] {currPos * 2, cnt+1});
			nextPos = currPos +1;
			if(nextPos>=0 && nextPos<=100000 && !visited[nextPos] ) 
            	que.offer(new int[] {currPos + 1, cnt+1});
			nextPos = currPos -1;
			if(nextPos>=0 && nextPos<=100000 && !visited[nextPos] ) 
            	que.offer(new int[] {currPos - 1, cnt+1});
		}		
		System.out.println(cnt);	
	}
}