구현 문제로 분류되어있지만 전형적인 BFS문제이다.(DFS로도 풀수는 있다)
클래스를 하나 만들어서 node와 count를 담게 한다음 큐에 넣는다.
1을 붙인다는 것은 n * 10 + 1이 된다는 뜻이다.
import java.util.*;
public class Main {
static long target,n;
public static class Count {
public long node,cnt;
public Count(long node, long cnt){
this.node = node;
this.cnt = cnt;
}
}
static void bfs(long node){
Queue<Count> que = new LinkedList<>();
que.add(new Count(node,0));
while (!que.isEmpty()){
Count p = que.poll();
if(p.node == target){
System.out.print(p.cnt + 1);
return;
}
if(p.node*2 <= target){
que.add(new Count(p.node*2 , p.cnt+1));
}
if(p.node*10 + 1 <= target){
que.add(new Count(p.node*10 + 1 , p.cnt+1));
}
}
System.out.print(-1);
return;
}
public static void main (String[]args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextLong();
target = scanner.nextLong();
bfs(n);
}
}
컴파일할 때 따로만든 클래스를 안넣어서 컴파일 에러가 떴었다..