File tree Expand file tree Collapse file tree 2 files changed +70
-0
lines changed
백준/Gold/11729. 하노이 탑 이동 순서 Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ # [ Gold V] 하노이 탑 이동 순서 - 11729
2+
3+ [ 문제 링크] ( https://www.acmicpc.net/problem/11729 )
4+
5+ ### 성능 요약
6+
7+ 메모리: 44816 KB, 시간: 260 ms
8+
9+ ### 분류
10+
11+ 재귀
12+
13+ ### 제출 일자
14+
15+ 2025년 8월 16일 10:14:21
16+
17+ ### 문제 설명
18+
19+ <p >세 개의 장대가 있고 첫 번째 장대에는 반경이 서로 다른 n개의 원판이 쌓여 있다. 각 원판은 반경이 큰 순서대로 쌓여있다. 이제 수도승들이 다음 규칙에 따라 첫 번째 장대에서 세 번째 장대로 옮기려 한다.</p >
20+
21+ <ol >
22+ <li>한 번에 한 개의 원판만을 다른 탑으로 옮길 수 있다.</li>
23+ <li>쌓아 놓은 원판은 항상 위의 것이 아래의 것보다 작아야 한다.</li>
24+ </ol >
25+
26+ <p >이 작업을 수행하는데 필요한 이동 순서를 출력하는 프로그램을 작성하라. 단, 이동 횟수는 최소가 되어야 한다.</p >
27+
28+ <p >아래 그림은 원판이 5개인 경우의 예시이다.</p >
29+
30+ <p style =" text-align : center ;" ><img alt =" " src =" " style =" height :200px ; width :1050px " ></p >
31+
32+ ### 입력
33+
34+ <p >첫째 줄에 첫 번째 장대에 쌓인 원판의 개수 N (1 ≤ N ≤ 20)이 주어진다.</p >
35+
36+ ### 출력
37+
38+ <p >첫째 줄에 옮긴 횟수 K를 출력한다.</p >
39+
40+ <p >두 번째 줄부터 수행 과정을 출력한다. 두 번째 줄부터 K개의 줄에 걸쳐 두 정수 A B를 빈칸을 사이에 두고 출력하는데, 이는 A번째 탑의 가장 위에 있는 원판을 B번째 탑의 가장 위로 옮긴다는 뜻이다.</p >
41+
Original file line number Diff line number Diff line change 1+ import java .io .*;
2+
3+ public class Main {
4+ static StringBuilder sb = new StringBuilder ();
5+ static int count = 0 ;
6+
7+ public static void main (String [] args ) throws Exception {
8+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
9+
10+ int n = Integer .parseInt (br .readLine ());
11+
12+ hanoi (n , 1 , 3 , 2 );
13+ System .out .println (count );
14+ System .out .print (sb );
15+ }
16+
17+ static void hanoi (int n , int from , int to , int mid ) {
18+ if (n == 1 ) {
19+ sb .append (from ).append (' ' ).append (to ).append ('\n' );
20+ count ++;
21+ return ;
22+ }
23+
24+ hanoi (n - 1 , from , mid , to );
25+ sb .append (from ).append (' ' ).append (to ).append ('\n' );
26+ count ++;
27+ hanoi (n - 1 , mid , to , from );
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments