Created
April 8, 2017 05:05
-
-
Save kd0g/e517429319a677458a0af01336f19883 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf8 | |
''' | |
사실 문제 자체가 기억 안나서 구글신에 물어볼 뻔. | |
n == 2일 때, 어떻게 움직이면 좋을지 move()를 여러번 적어놓고 해결한 다음, | |
move(1, 3) | |
move(1, 2) | |
move(2, 3) | |
pp()를 만들고, | |
자 이제 이걸 재귀로 바꿔볼까? | |
하는데 금방 풀림. | |
''' | |
class HanoiTower: | |
def __init__(self, height=1): | |
''' | |
봉1 봉2 봉3 | |
''' | |
self.n = height | |
def setup(self): | |
''' | |
setup | |
''' | |
b1 = [str(x) for x in range(1, 1+self.n)] | |
b1.reverse() | |
self.b1, self.b2, self.b3 = b1, [], [] | |
def pp(self): | |
''' | |
pretty print | |
''' | |
print("** 기왕 하노이에 왔으니 탑을 움직여봅시다 **") | |
print("B1|%s" % " ".join(self.b1)) | |
print("B2|%s" % " ".join(self.b2)) | |
print("B3|%s" % " ".join(self.b3)) | |
def move(self, from_, to_): | |
''' | |
popping, pushing | |
''' | |
to_.append(from_.pop(-1)) | |
def move_tower(self, n, src, dst, mid): | |
''' | |
move. | |
''' | |
if n == 1: | |
self.pp() | |
self.move(src, dst) | |
return | |
self.move_tower(n-1, src, mid, dst) | |
self.pp() | |
self.move(src, dst) | |
self.move_tower(n-1, mid, dst, src) | |
def run(self): | |
self.setup() | |
src, dst, mid = self.b1, self.b3, self.b2 | |
self.move_tower(self.n, src, dst, mid) | |
self.pp() | |
HanoiTower(3).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment