Skip to content

Commit 602a30c

Browse files
authored
Merge pull request #1115 from AlgorithmWithGod/ksinji
[20251014] BOJ / G5 / 하노이 탑 / 강신지
2 parents 2c670b8 + 1b8243e commit 602a30c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
```java
2+
import java.io.*;
3+
import java.math.BigInteger;
4+
5+
public class Main {
6+
static int N;
7+
static StringBuilder sb = new StringBuilder();
8+
9+
public static void main(String[] args) throws Exception {
10+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
N = Integer.parseInt(br.readLine());
12+
13+
BigInteger moves = BigInteger.valueOf(2).pow(N).subtract(BigInteger.ONE);
14+
sb.append(moves).append('\n');
15+
16+
if (N <= 20) {
17+
hanoi(N, 1, 3, 2);
18+
}
19+
20+
System.out.print(sb.toString());
21+
}
22+
23+
// N개를 from -> to
24+
static void hanoi(int N, int from, int to, int temp) {
25+
if (N == 0) return;
26+
hanoi(N - 1, from, temp, to); // N-1개를 출발 -> 보조 기둥으로 옮김
27+
sb.append(from).append(' ').append(to).append('\n'); // 출발 -> 목적 기둥으로 남은 원판(젤 큰 거) 옮김
28+
hanoi(N - 1, temp, to, from); // N-1개를 보조 -> 목적 기둥으로 옮김
29+
}
30+
}
31+
```

0 commit comments

Comments
 (0)