Data Structures & Algorithms

Recursion: tower of hanoi

neal89 2025. 3. 3. 15:04

First approach...

public class HanoiTower {
  // 재귀 메서드: 하노이의 탑 이동 수행
  public static void hanoi(int n, char start, char end, char another) {
    if (n == 1) { // 종료 조건: 원반이 1개일 때
      System.out.println("Move 1 from " + start + " to " + end);
      return;
    }
    hanoi(n - 1, start, another, end);
    System.out.println("Move " + n + " from " + start + " to " + end);
    hanoi(n - 1, another, end, start);
  }
  public static void main(String[] args) {
    int numDisks = 3;
    hanoi(numDisks, 'A', 'C', 'B');
  }
}