
-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);
}
}
이전 하노이의 탑 문제를 참고하여 해결했습니다.
'알고리즘 문제 > Java' 카테고리의 다른 글
| [프로그래머스/Java] 시소 짝꿍 (0) | 2026.05.06 |
|---|---|
| [프로그래머스/Java] 광물 캐기 (0) | 2026.05.05 |
| [프로그래머스/Java] 가장 큰 정사각형 찾기 (0) | 2026.05.03 |
| [프로그래머스/Java] 줄 서는 방법 (0) | 2026.05.02 |
| [프로그래머스/Java] 리코쳇 로봇 (0) | 2026.05.01 |