Skip to content

Commit b8d055f

Browse files
solution: level 2 / 하노이 탑 풀이 추가
1 parent 68d03df commit b8d055f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

level-2/하노이의-탑.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//https://github.com/codeisneverodd/programmers-coding-test
2+
//완벽한 정답이 아닙니다.
3+
//정답 1 - codeisneverodd
4+
function solution(n) {
5+
return move(1, 3, 2, n);
6+
}
7+
const move = (departure, destination, waypoint, numberOfPlate) => {
8+
if (numberOfPlate === 1) return [[departure, destination]];
9+
return [
10+
...move(departure, waypoint, destination, numberOfPlate - 1),
11+
...move(departure, destination, waypoint, 1),
12+
...move(waypoint, destination, departure, numberOfPlate - 1),
13+
];
14+
};
15+
//재귀를 생각해보기에 좋은 문제입니다.
16+
//추천 레퍼런스 https://shoark7.github.io/programming/algorithm/tower-of-hanoi
17+
/*
18+
n개가 있다면
19+
1. 1->2로 n-1개를 옮김
20+
2. 1->3으로 가장 큰 1개를 옮김
21+
3. 2->1로 n-2개를 옮김
22+
4. 2->3으로 2번에 있는 것 중 가장 큰 1개를 옮김
23+
의 반복
24+
25+
결국 무엇이든 a -> b 로 n 를 옮기는 동작의 반복이므로 이를 재귀로 표현하면 됨.
26+
a->b 로 n 을 옮기는 것은 a->c로 n-1개를 옮겨놓고, a->b로 하나를 옮긴 후, c->b로 n-1개를 옮기는 것의 반복
27+
함수에서 a는 depature(출발지), b는 destination(도착지), c는 waypoint(경유지)로 작성되어있음.
28+
*/

0 commit comments

Comments
 (0)