문제 링크: https://www.acmicpc.net/problem/11729
백준 재귀 6단계 - 11729번 하노이 탑 이동 순서를 풀어보았다.
풀이: 하노이 탑을 재귀함수로 작성하면 된다.
C++
#include <iostream>
#include<cmath>
using namespace std;
void hanoi(int k,int a, int b, int c)
{
if(k==1) printf("%d %d\n",a,b);
else
{
hanoi(k-1,a,c,b);
printf("%d %d\n",a,b);
hanoi(k-1,c,b,a);
}
}
int main()
{
int n;
scanf("%d",&n);
cout << (int)pow(2,n)-1 << "\n";
hanoi(n,1,3,2);
}
Python
import math
def hanoi(t,a,b,c):
if t==1: print(a,b)
else:
hanoi(t-1,a,c,b)
print(a,b)
hanoi(t-1,c,b,a)
n=int(input())
print(int(math.pow(2,n))-1) # 옮긴 횟수
hanoi(n,1,3,2)
Java
'코테용 문제풀이 > 백준' 카테고리의 다른 글
분해합 풀이 (0) | 2023.01.06 |
---|---|
블랙잭 풀이 (0) | 2023.01.06 |
별 찍기 - 10 풀이 (0) | 2023.01.05 |
알고리즘 수업 - 병합 정렬 1 풀이 (0) | 2023.01.05 |
재귀의 귀재 풀이 (0) | 2023.01.05 |