티스토리 뷰
https://programmers.co.kr/learn/courses/30/lessons/12946
코딩테스트 연습 - 하노이의 탑
하노이 탑(Tower of Hanoi)은 퍼즐의 일종입니다. 세 개의 기둥과 이 기동에 꽂을 수 있는 크기가 다양한 원판들이 있고, 퍼즐을 시작하기 전에는 한 기둥에 원판들이 작은 것이 위에 있도록 순서대��
programmers.co.kr
재귀를 이용해 구현하였습니다.
C++ 소스 코드
#include <vector>
#include <string>
using namespace std;
vector<vector<int>> answer;
void hanoi(int n, int from, int to, int tmp){
vector<int> temp = { from, to };
if (n == 1) answer.push_back(temp);
else{
hanoi(n-1, from, tmp, to);
answer.push_back(temp);
hanoi(n-1, tmp, to, from);
}
}
vector<vector<int>> solution(int n){
hanoi(n, 1, 3, 2);
return answer;
}
Swift 소스 코드
import Foundation
func solution(_ n:Int) -> [[Int]] {
var answer: [[Int]] = []
func hanoi(n: Int, from: Int, to: Int, via: Int){
let tmp: [Int] = [from, to]
if n == 1 {
answer.append(tmp)
}else {
hanoi(n: n-1,from: from, to: via, via: to)
answer.append(tmp)
hanoi(n: n-1, from: via, to: to, via: from)
}
}
hanoi(n: n, from: 1, to: 3, via: 2)
return answer
}
'Algorithm > 알고리즘 문제풀이' 카테고리의 다른 글
BOJ) 9375 - 패션왕 신해빈 (0) | 2020.07.27 |
---|---|
프로그래머스) Lv3 - 방문 길이 (0) | 2020.07.25 |
프로그래머스) Lv3 - 행렬의 곱셈 (0) | 2020.07.19 |
프로그래머스) Lv3 - 배달 (1) | 2020.07.14 |
BOJ) 15732 - 도토리 숨기기 (0) | 2020.07.13 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- UIHostingController
- C++
- 프로그래머스
- Swift unowned
- disposeBag
- Swift
- coreml
- infallible
- ARKit
- 카카오인턴십
- ios
- 코코아팟
- SwiftUI
- cocoapods
- 백준온라인저지
- 백준
- blendshapes
- blendshape
- 안드로이드
- boj
- 알고리즘
- SWEA
- rxswift
- GraphDB
- rxswift6
- Kotlin
- Swift weak
- DispatchQueue
- Reactivex
- Lottie
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함