[프로그래머스] 코딩테스트 연습 - 연습문제 Level 3 하노이의 탑

uoahy·2021년 10월 5일
0

Solution.java

class Solution {
    int i = 0;
    
    public int[][] solution(int n) {
        int[][] answer = new int[(int) Math.pow(2, n) - 1][2];
        
        hanoi(1, 3, n, answer);
        
        return answer;
    }
    
    void hanoi(int from, int to, int n, int[][] ans) {
        if(n == 1) {
            ans[i][0] = from;
            ans[i][1] = to;
            i++;
            return;
        }

        hanoi(from, 6-from-to, n-1, ans);
        ans[i][0] = from;
        ans[i][1] = to;
        i++;
        hanoi(6-from-to, to, n-1, ans);
    }
}

혼자 규칙을 찾기 힘들어 인터넷에서 하노이의 탑 공식을 참고하여 풀었다.

다음에 한 번 더 공부해봐야겠다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글