본문 바로가기
알고리즘 문제/Java

[프로그래머스/Java] 하노이의 탑

by 현장 2026. 5. 4.

-Code

class Solution {
    static int idx = 0;
    public int[][] solution(int n) {
        int len = (int) Math.pow(2, n) - 1;
        int[][] answer = new int[len][2];
        hanoi(answer, n, 1, 3, 2);
        return answer;
    }

    private void hanoi(int[][] answer, int distCnt, int start, int end, int other) {
        // 위에 원판이 없는 경우
        if (distCnt == 1) {
            answer[idx++] = new int[] {start, end};
            return;
        }
        // 시작점과 목적지가 아닌 위치로 이동
        hanoi(answer, distCnt - 1, start, other, end);
        // 위의 원판을 경유지에 옮긴 후 현재 원판을 옮김
        answer[idx++] = new int[] {start, end};
        // 경유지에 있는 원판 목적지로 옮김
        hanoi(answer, distCnt - 1, other, end, start);
    }
}

이전 하노이의 탑 문제를 참고하여 해결했습니다.