백준
[백준] 1697 숨바꼭질
거북이같은곰
2021. 11. 25. 22:46
https://smartpro.tistory.com/18
[백준/1697/Java] 숨바꼭질 - BFS 풀이
BFS (너비 우선 탐색, Breadth-First Search) 알고리즘에서 기본적인 문제 하나를 풀어보도록 하겠습니다. 문제 1697번: 숨바꼭질 (acmicpc.net) 1697번: 숨바꼭질 수빈이는 동생과 숨바꼭질을 하고 있다. 수
smartpro.tistory.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int[] check = new int[100001];
int[] cnt = new int[100001];
Queue q = new LinkedList<Integer>();
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
if(N == K)
System.out.println(0);
else {
q.add(N);
while(!q.isEmpty()) {
if(check[K] != 0)
break;
N = (int) q.remove();
if(N-1 >= 0) {
if(check[N-1] == 0) {
check[N-1] = check[N] + 1; //초
q.add(N-1);
}
}
if(N + 1 < 100001) {
if(check[N+1] == 0) {
check[N+1] = check[N] + 1;
q.add(N+1);
}
}
if(N * 2 < 100001) {
if(check[N*2] == 0) {
check[N*2] = check[N] + 1;
q.add(N*2);
}
}
}
System.out.println(check[K]);
}
}
}