programmers_하노이의 탑_java
2023. 5. 15. 12:56ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/12946
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);
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_혼자 놀기의 달인_java (0) | 2023.05.15 |
---|---|
programmers_숫자 카드 나누기_java (0) | 2023.05.15 |
programmers_문자열 압축_java (0) | 2023.05.15 |
programmers_마법의 엘리베이터_java (0) | 2023.05.14 |
programmers_호텔 대실_java (0) | 2023.05.12 |