반응형
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[] Min = new int[100005];
static int N;
static int K;
public static int bfs(int n, int k, int[] min) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(n);
int move[] = new int[3];
Min[n] = 0;
int next = n;
while(!q.isEmpty() && next != k) {
next = q.poll();
move[0] = next - 1;
move[1] = next + 1;
move[2] = next*2;
for (int i = 0; i < move.length; i++) {
if(move[i] >= 0 && move[i] <= 100000) {
if (Min[move[i]] == -1) {
q.add(move[i]);
Min[move[i]] = Min[next] +1;
}
}
}
}
return Min[k];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
K = sc.nextInt();
Arrays.fill(Min, -1);
System.out.println(bfs(N,K,Min));
}
}
반응형
LIST
'알고리즘 > 연습문제' 카테고리의 다른 글
백준 - 11399 ATM(feat. java) (0) | 2019.08.13 |
---|---|
백준 - 7576 토마토(feat. java) (0) | 2019.08.12 |
백준 2667 - 단지번호 붙이기(feat. java) (0) | 2019.08.12 |
백준 2178 - 미로찾기(feat. java) (0) | 2019.08.12 |
백준 1260 : DFS와 BFS (feat. java) (0) | 2019.08.12 |