fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // 1 ~ N을 완성하기 위해서는, 1 ~ N - 1이 완성되어야 한다.
  5. // -> 재귀 느낌이 난다.
  6. // 재귀에서 상태 -> 파라미터화
  7. // 상태 : N - 1, 어디서부터, 어디로
  8. // n <= 20, O(2^n)은 가능
  9.  
  10. int n;
  11.  
  12. // k - 1번이 x에서 y로 움직이고, 바닥이 움직이고, 다시 4번이 y에서 z로움직인다.
  13. void hanoi(int k, int from, int to) {
  14. if (k == 0) return;
  15. int middle = 6 - from - to;
  16. hanoi(k - 1, from, middle);
  17. cout << from << " " << to << '\n';
  18. hanoi(k - 1, middle, to);
  19. }
  20.  
  21.  
  22. int main(void) {
  23. cin.tie(0)->sync_with_stdio(false);
  24. cin >> n;
  25. hanoi(n, 1, 3);
  26. }
Success #stdin #stdout 0s 5288KB
stdin
3
stdout
1 3
1 2
3 2
1 3
2 1
2 3
1 3