하노이탑은 결국, n-1개의 블록을 1번 기둥에서 2번 기둥으로 옮기는 것 + n번째 블록을 1번 블록에서 3번 블록으로 옮기는 것 + n-1개의 블록을 2번기둥에서 3번 기둥으로 옮기는 것 으로 정의된다.
총 이동 횟수는 2^n - 1 번 이다.
각 라인을 그때마다 출력한느 것이 아니라, StringBuffer를 이용해 저장한 후 마지막에 한번에 출력해야 시간초과가 안난다.
import java.util.*;
public class Main{
private static StringBuffer sb = new StringBuffer();
private static void f(int n,int from, int tmp, int to) {
if(n==1) {
sb.append(from+" "+to+"\n");
}else {
f(n-1,from,to,tmp);
sb.append(from+" "+to+"\n");
f(n-1,tmp,from,to);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int count = (int)Math.pow(2, n)-1;
System.out.println(count);
f(n,1,2,3);
System.out.print(sb.toString());
}
}
'Algorithm' 카테고리의 다른 글
[CodeGround] Practice - 숫자 골라내기 (0) | 2021.07.20 |
---|---|
백준 1874 스택수열 풀이 (0) | 2020.09.30 |
메이플 스타포스 시뮬레이터 (0) | 2020.09.27 |
백준 1316 그룹단어체커 문제풀이 (0) | 2020.06.09 |
백준 1157번 단어공부 풀이 (0) | 2020.06.09 |