์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Python

[BOJ/Step10] 11729 : ํ•˜๋…ธ์ด ํƒ‘ ์ด๋™ ์ˆœ์„œ (Python)

NaNaRin๐Ÿ™ƒ 2021. 2. 17. 21:25

www.acmicpc.net/problem/11729

 

11729๋ฒˆ: ํ•˜๋…ธ์ด ํƒ‘ ์ด๋™ ์ˆœ์„œ

์„ธ ๊ฐœ์˜ ์žฅ๋Œ€๊ฐ€ ์žˆ๊ณ  ์ฒซ ๋ฒˆ์งธ ์žฅ๋Œ€์—๋Š” ๋ฐ˜๊ฒฝ์ด ์„œ๋กœ ๋‹ค๋ฅธ n๊ฐœ์˜ ์›ํŒ์ด ์Œ“์—ฌ ์žˆ๋‹ค. ๊ฐ ์›ํŒ์€ ๋ฐ˜๊ฒฝ์ด ํฐ ์ˆœ์„œ๋Œ€๋กœ ์Œ“์—ฌ์žˆ๋‹ค. ์ด์ œ ์ˆ˜๋„์Šน๋“ค์ด ๋‹ค์Œ ๊ทœ์น™์— ๋”ฐ๋ผ ์ฒซ ๋ฒˆ์งธ ์žฅ๋Œ€์—์„œ ์„ธ ๋ฒˆ์งธ ์žฅ๋Œ€๋กœ

www.acmicpc.net


n๊ฐœ์˜ ์›ํŒ์„ 1๋ฒˆ ์žฅ๋Œ€์—์„œ 3๋ฒˆ ์žฅ๋Œ€๋กœ ์˜ฎ๊ธฐ๋ ค๋ฉด

   1. n-1๊ฐœ์˜ ์›ํŒ์„ 1๋ฒˆ ์žฅ๋Œ€(์ถœ๋ฐœ)์—์„œ 2๋ฒˆ ์žฅ๋Œ€(์ค‘๊ฐ„)๋กœ ์˜ฎ๊ธด๋‹ค : ์žฌ๊ท€

   2. ๊ฐ€์žฅ ํฐ ์›ํŒ์„ 1๋ฒˆ ์žฅ๋Œ€(์ถœ๋ฐœ)์—์„œ 3๋ฒˆ ์žฅ๋Œ€(๋„์ฐฉ)๋กœ ์˜ฎ๊ธด๋‹ค

   3. n-1๊ฐœ์˜ ์›ํŒ์„ 2๋ฒˆ ์žฅ๋Œ€(์ค‘๊ฐ„)์—์„œ 3๋ฒˆ ์žฅ๋Œ€(๋„์ฐฉ)๋กœ ์˜ฎ๊ธด๋‹ค : ์žฌ๊ท€

3๊ฐœ์˜ ๊ณผ์ •์„ ๊ฑฐ์น˜๊ณ  ์ด 2^n + 1๋ฒˆ ์ด๋™์ด ํ•„์š”ํ•˜๋‹ค. 

์œ„ ๊ณผ์ •์„ ๊ตฌํ˜„ํ•˜๋ฉด hanoi(n, start, middle, goal) ์ด ๋œ๋‹ค.

# 11729.py

def hanoi(n, start, middle, goal):
    if n == 1:
        print(f'{start} {goal}')
    else:
        hanoi(n-1, start, goal, middle)
        print(f'{start} {goal}')
        hanoi(n-1, middle, start, goal)


n = int(input())
print(2 ** n - 1)
hanoi(n, 1, 2, 3)