728x90
import java.util.*;
class Main {
private static int N; //수빈이 위치
private static int K; //동생 위치
private static boolean[] isVisited = new boolean[100001];
private static int answer = Integer.MAX_VALUE;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
K = sc.nextInt();
bfs();
System.out.println(answer);
sc.close();
}
static void bfs() {
PriorityQueue<Point> queue = new PriorityQueue<>();
queue.offer(new Point(N, 0));
while (!queue.isEmpty()) {
Point point = queue.poll();
if(isVisited[point.pos]) continue;
isVisited[point.pos] = true;
if (point.pos == K) {
answer = Math.min(point.count, answer);
}
if (point.pos * 2 <= 100000 && !isVisited[point.pos * 2]) { // 0초 순간이동
queue.offer(new Point(point.pos * 2, point.count));
}
if (point.pos + 1 <= 100000 && !isVisited[point.pos + 1]) { //1초 한칸우측
queue.offer(new Point(point.pos + 1, point.count + 1));
}
if (point.pos - 1 >= 0 && !isVisited[point.pos - 1]) { //1초 한칸좌측
queue.offer(new Point(point.pos - 1, point.count + 1));
}
}
}
private static class Point implements Comparable<Point>{
int pos;
int count;
public Point(int pos, int count) {
this.pos = pos;
this.count = count;
}
@Override
public int compareTo(Point o) {
return count - o.count;
}
}
}
bfs로 풀리는 문제였다.. 다른사람들 풀이 참고
728x90
'CS > Algorithm' 카테고리의 다른 글
[ 백준:2617/JAVA ] 구슬찾기 (0) | 2021.09.08 |
---|---|
[백준:11404 / JAVA] 플로이드 (0) | 2021.09.07 |
[ 백준 : 1916/JAVA ] 최소비용 구하기 (0) | 2021.09.05 |
[백준 : 1753 / JAVA] 최단경로 (0) | 2021.09.05 |
[ JAVA / 백준 : 1699 ] 제곱수의 합 (0) | 2021.08.22 |