programmers_하노이의 탑_java

2023. 5. 15. 12:56Algorithm/Programmers

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/12946

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

import java.util.*;

class Solution {
    public int[][] solution(int n) {
        int[][] answer = {};

        List<int[]> resList = new ArrayList<>();
        hanoi(n, 1, 2,3, resList);

        answer = new int[resList.size()][2];
        int idx = 0;
        for (int[] res : resList){
            answer[idx][0] = res[0];
            answer[idx++][1] = res[1];
        }

        return answer;
    }

    public void hanoi(int N, int from, int mid, int to, List<int[]> res){
        // 이동할 원판이 1개
        if(N == 1){
            res.add(new int[]{from, to});
            return;
        }

        // n-1개 from -> mid
        hanoi(N-1, from, to, mid, res);
        // 1개 L -> R
        res.add(new int[]{from, to});
        // N-1개를 mid -> to
        hanoi(N-1, mid, from, to, res);
    }
}