Algorithm

[BOJ] 11729. 하노이 탑 이동 순서

프로그래민 2020. 3. 22. 17:11
반응형

재귀를 사용하는 대표적인 문제이다.

N개의 원판을 옮기려면 크게 3가지 부분으로 생각하여 접근할 수 있다. 첫번째로 N-1개의 원판을 목적지가 아닌 중간 지점 고리로 옮겨놓고, 두번째로는 가장 밑바닥에 위치한 원판을 목적지로 옮긴다. 마지막으로 중간지점에 위치해있던 N-1개의 원판을 목적지 고리로 옮기는 과정을 반복하다보면 전체 N개의 원판을 목적지로 옮기는 것이 가능하다. 재귀함수의 기저조건으로는 옮길 원판이 없는 경우를 사용하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package chap06;
 
 
public class Main_bj_11729_재귀 {
    static StringBuilder sb;
    static int total;
    
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int circle = Integer.parseInt(br.readLine());
        sb=new StringBuilder();
        
        total=0;
        hanoi(circle,1,2,3);
        System.out.println(total);
        System.out.println(sb.toString());
        
    }
    static void hanoi(int circle,int start,int temp, int dest) {
        if(circle==0)
            return;
        
        hanoi(circle-1, start, dest, temp);    //n-1개를 중간지점으로 옮기기
        sb.append(start + " "+dest+"\n");
        total++;
        hanoi(circle-1,temp,start,dest);    //중간지점에 있는 n-1개를 최종지점으로 옮기기
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
                                               
반응형

'Algorithm' 카테고리의 다른 글

[BOJ] 2448. 별 찍기-11  (0) 2020.03.23
[BOJ] 1074. Z  (0) 2020.03.22
[BOJ] 1629. 곱셈  (0) 2020.03.22
[BOJ] 2146. 다리 만들기  (0) 2020.03.21
[BOJ] 12851. 숨바꼭질2  (0) 2020.03.18