๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 11729 ํ•˜๋…ธ์ด ํƒ‘ ์ด๋™ ์ˆœ์„œ

๋ฐ˜์‘ํ˜•

[BOJ] 11729 ํ•˜๋…ธ์ดํƒ‘ ์ด๋™ ์ˆœ์„œ

https://www.acmicpc.net/problem/11729

๋ฌธ์ œ ์ ‘๊ทผ

์ผ๋‹จ ํ•˜๋…ธ์ด ํƒ‘์„ 1์—์„œ 2๋ฅผ ๊ฑฐ์ณ์„œ(์ด์šฉํ•ด์„œ?) 3์œผ๋กœ ์˜ฎ๊ฒจ์•ผ ํ•œ๋‹ค.
๋‚˜์˜ ์ง๊ด€์ ์ธ? ์ ‘๊ทผ ๋ฐฉ์‹์€ n์ด 3๊ฐœ์ผ ๋•Œ,
1.์ฒซ ํ•จ์ˆ˜ ํ˜ธ์ถœ๋กœ 1 -> 3์œผ๋กœ ๊ฐ€์žฅ ์ž‘์€ ๊ฒƒ์„ ์˜ฎ๊ธด๋‹ค.
2.๊ทธ๋ฆฌ๊ณ  ๋‹ค์‹œ ํ•จ์ˆ˜ ํ˜ธ์ถœ๋กœ 1 -> 2๋กœ ๋‘๋ฒˆ์งธ๋กœ ์ž‘์€ ๊ฒƒ์„ ์˜ฎ๊ธด๋‹ค. (์ด๋Ÿฌ๋ฉด ๊ฐ€์žฅ ํฐ๊ฒƒ์ด 1์— ์žˆ๋‹ค!)
3.์ด๋•Œ๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ ํ•˜์ง€ ์•Š๊ณ  1 -> 3์œผ๋กœ ์˜ฎ๊ธด๋‹ค. (์ด ๋•Œ 3์— ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ๊ฒƒ์€ ์ด์ œ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋„ ๋œ๋‹ค!)
4.์ด์ œ ์ด ๋ฌธ์ œ๋Š” 2๊ฐœ์˜ ์›๋ฐ˜์„ ๊ฐ€์ง„ ํ•˜๋…ธ์ดํƒ‘์„ 2 -> 3์œผ๋กœ ์˜ฎ๊ธฐ๋Š” ๋ฌธ์ œ๋กœ ์ž‘์•„์ง„๋‹ค. => ํ•จ์ˆ˜ ํ˜ธ์ถœ๋กœ 2->3์œผ๋กœ ๋‹ค์‹œ ์ž‘์€ ๊ฒƒ์„ ์˜ฎ๊ธด๋‹ค.

์ด ์ ‘๊ทผ์„ ์žฌ๊ท€์ ์œผ๋กœ ์ž˜ ์ •๋ฆฌํ•˜๋ฉด ์ด๋ ‡๊ฒŒ ๋œ๋‹ค.
1.1 -> 3์œผ๋กœ n๊ฐœ๋ฅผ ์˜ฎ๊ธฐ๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ ํ•œ๋‹ค.
2.1 -> 2๋กœ n-1๊ฐœ๋ฅผ ์˜ฎ๊ธฐ๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ ํ•œ๋‹ค.
3.1 -> 3์œผ๋กœ ๊ฐ€์žฅ ํฐ ์›๋ฐ˜์„ ์˜ฎ๊ธด๋‹ค.
4.2->3 ์œผ๋กœ n-1๊ฐœ์˜ ์›๋ฐ˜์„ ์˜ฎ๊ธฐ๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

Code

import java.util.Scanner;

public class BOJ11729 {
    static int cnt = 0;
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        hanoi(n,1,3,2);
        System.out.println(cnt);
        System.out.println(sb);
    }
    public static void hanoi(int n, int from, int to, int by){
        if(n == 1){
            move(from, to);
        } else {
            hanoi(n-1,from,by,to);
            move(from,to);
            hanoi(n-1,by,to,from);
        }
    }
    private static void move(int from, int to) {
        sb.append(from + " " + to+"\n");
        cnt++;
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

์˜ˆ์ „์— ํ•˜๋…ธ์ด ํƒ‘์„ ์ ‘ํ–ˆ์„ ๋•Œ๋Š” ๋˜๊ฒŒ ์–ด๋ ค์› ๋Š”๋ฐ, ํ•™๋…„์ด ์˜ฌ๋ผ๊ฐ€์„œ ๊ทธ๋Ÿฐ๊ฐ€ ์ดํ•ด๊ฐ€ ์ž˜ ๋˜๋Š”๋Š๋‚Œ์ด๋‹ค!

๋ฐ˜์‘ํ˜•