๋ 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);
}
}
'์๊ณ ๋ฆฌ์ฆ > ๋ฌธ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ] ๋ฐฑ์ค 11404 - ํ๋ก์ด๋ (0) | 2020.12.19 |
---|---|
[์๋ฐ] ๋ฐฑ์ค 2206 - ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ (0) | 2020.12.12 |
[์๋ฐ] ๋ฐฑ์ค 7576 - ํ ๋งํ (0) | 2020.12.12 |
[์๋ฐ] ๋ฐฑ์ค 1753 - ์ต๋จ๊ฒฝ๋ก (0) | 2020.12.06 |
[์๋ฐ] ๋ฐฑ์ค 1012 - ์ ๊ธฐ๋ ๋ฐฐ์ถ (0) | 2020.12.06 |