문제


일단 생각하기!
- 재귀로 풀어야함은 알았지만 도저히 어떻게 풀어야할지 감이 잡히지 않아 다른 사람의 풀이를 참고했다.. 다시 풀어보고 이해를 마쳤다!
- 1번 장대에서 3번 장대로 모든 원판들을 옮기려면 가장 아래의 원판, 즉 n번째 원판을 3번 장대로 옮겨야하므로 다른 장대(=2번 장대)로 나머지 원판들을 옮겨놔야 한다. 이 부분은
hanoi(n - 1, from, other, to);로 구현할 수 있다. from은 출발 장대, to는 도착 장대, other는 출발, 도착 장대도 아닌 나머지 장대다.
- 문제의 요구에 따라
from과 to를 출력한 뒤 n번째 장대를 3번째로 옮겨야하므로 hanoi(n - 1, other, to, from);과 같이 구현했다.
- 기저조건은
n이 0일때다!
풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int count = 0;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
hanoi(n, 1, 3, 2);
System.out.println(count);
System.out.println(sb);
}
static void hanoi(int n, int from, int to, int other) {
if (n == 0) return;
count++;
hanoi(n - 1, from, other, to);
sb.append(from).append(" ").append(to).append("\n");
hanoi(n - 1, other, to, from);
}
}