하노이의 탑

han.user();·2023년 4월 7일
0

프로그래머스

목록 보기
46/87
post-thumbnail

import java.util.ArrayList;

class Solution {
    public ArrayList<int[]> answer = new ArrayList<int[]>();

    public int[][] solution(int n) {
        hanoi(n, 1, 3, 2); // 하노이 탑 알고리즘 실행
        int[][] answerArray = new int[answer.size()][2];
        for (int i = 0; i < answer.size(); i++) {
            answerArray[i] = answer.get(i); // 리스트를 배열로 변환
        }
        return answerArray;
    }

    public void hanoi(int n, int from, int to, int via) {
        if (n == 1) { // 원판이 하나일 경우
            int[] move = {from, to}; // 원판을 옮긴 기둥 번호 저장
            answer.add(move); // 답 리스트에 추가
            return;
        }

        hanoi(n - 1, from, via, to); // n-1개의 원판을 2번 기둥으로 이동
        int[] move = {from, to}; // n번째 원판을 3번 기둥으로 이동
        answer.add(move); // 답 리스트에 추가
        hanoi(n - 1, via, to, from); // 2번 기둥에 있는 n-1개의 원판을 3번 기둥으로 이동
    }
}
profile
I'm still hungry.

0개의 댓글