[BOJ] 11729. 하노이 탑 이동 순서
15 Apr 2026
Reading time ~1 minute
풀이
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println((1<<n) - 1);
StringBuilder sb = solve(n,1,3,2);
System.out.println(sb);
}
// solve(n,from,to,by) : n개를 from에서 by를 거쳐 to로 옮기는 함수.
public static StringBuilder solve(int n, int from, int to, int by) {
StringBuilder sb = new StringBuilder();
if(n == 1) {
sb.append(move(from, to));
return sb;
}
sb.append(solve(n-1,from,by,to));
sb.append(move(from,to));
sb.append(solve(n-1,by, to,from));
return sb;
}
// move(from,to) : 1개를 from에서 to로 옮기는 함수.
public static StringBuilder move(int from, int to) {
StringBuilder sb = new StringBuilder(from + " " + to + "\n");
return sb;
}
}