반응형
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(); //수빈의 위치
int k=sc.nextInt(); //동생의 위치
boolean visited []=new boolean [100001];
Arrays.fill(visited, false);
visited[n]=true;
//걸음수를 넣는 배열
int status[]=new int [100001];
status[0]=n;
Queue <Integer> q =new LinkedList<>();
//수빈이 위치가 더 크면 -1을 반복해서 만나는 경우밖에 없음
if(n>k) {
System.out.println(n-k);
}
//같으면 0 출력
else if(n==k) {
System.out.println(0);
}
else {
q.offer(n);
status[n] = 1; //지금위치 = 첫번째 걸음
boolean flag=true;
while(!q.isEmpty()&&flag) {
int now = q.poll();
for(int i=0; i<3; i++) {
int next;
if(i == 0)
next = now - 1;
else if(i == 1)
next = now + 1;
else
next = now * 2;
if(next == k) { //인덱스로 들어갈 숫자가 동생위치일때 status를 보면 몇걸음째인지 있겠지
System.out.println(status[now]);
flag=false;
break;
}
if(0 <= next && next <= 100000) {
if(status[next] == 0) {
q.offer(next);
//한걸음 더 가니까 next 위치의 걸음수는 now 위치의 걸음수+1
status[next] = status[now] + 1;
}
}
}
}
}
}
}
반응형
'개발 관련 공부 > 알고리즘' 카테고리의 다른 글
유니온 파인드 (1) | 2022.09.16 |
---|---|
백준 11725 트리의 부모 찾기 (0) | 2021.08.26 |
백준 7569 토마토2 (0) | 2021.08.24 |
백준 7576 토마토 (0) | 2021.08.23 |
백준 1302 베스트셀러 (0) | 2021.08.20 |
댓글