Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- BFS
- 세그먼트 트리
- 프로그래머스
- mst
- JUnit 5
- 구현
- 플로이드-와샬
- Network
- 이분탐색
- 투 포인터
- 그리디
- 수학
- dfs
- swea
- 시뮬레이션
- 위상정렬
- Effective Java
- 완전탐색
- 알고리즘
- Kotlin
- 유니온 파인드
- 동적계획법
- 백준
- CS
- 후니의 쉽게 쓴 시스코 네트워킹
- 스택
- 에라토스테네스의 체
- 문자열
- 백트래킹
- java
Archives
반갑습니다!
[프로그래머스] 하노이의 탑 본문
풀이
하노이의 탑은 전형적인 재귀 문제이다. 하노이의 탑에 대한 원리는 해당 영상을 보면 쉽게 이해할 수 있다. 하노이의 탑에 대한 원리만 파악한다면 쉽게 해결할 수 있는 문제이다.
코드
C++
#include <string>
#include <vector>
using namespace std;
vector<vector<int>> ans;
void hanoi(int n, int from, int to, int by) {
if (n == 1) {
ans.push_back({ from, to });
return;
}
hanoi(n - 1, from, by, to);
ans.push_back({ from, to });
hanoi(n - 1, by, to, from);
}
vector<vector<int>> solution(int n) {
vector<vector<int>> answer;
hanoi(n, 1, 3, 2);
answer = ans;
return answer;
}
Java
import java.util.ArrayList;
import java.util.List;
class Solution {
List<int[]> moves = new ArrayList<>();
public void move(int from, int to) {
moves.add(new int[]{from, to});
}
public void hanoi(int n, int from, int to, int by) {
if (n == 1) {
moves.add(new int[]{from, to});
return;
}
hanoi(n - 1, from, by, to);
moves.add(new int[]{from, to});
hanoi(n - 1, by, to, from);
}
public int[][] solution(int n) {
hanoi(n, 1, 3, 2);
int[][] answer = new int[moves.size()][2];
for (int i = 0; i < answer.length; i++)
answer[i] = new int[]{moves.get(i)[0], moves.get(i)[1]};
return answer;
}
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 야근 지수 (0) | 2020.09.04 |
---|---|
[프로그래머스] N-Queen (0) | 2020.09.03 |
[프로그래머스] 이중우선순위큐 (0) | 2020.09.02 |
[프로그래머스] 3 x n 타일링 (0) | 2020.09.02 |
[프로그래머스] 기둥과 보 설치 (0) | 2020.09.02 |