본문 바로가기

Algorithm

하노이탑(재귀) Python

cnt = 0
def hanoimove(num, fromm, by, to):
    global cnt
    cnt += 1
    if num == 1:
        #print("%d이 %c에서 %c로 이동 " % (num, fromm, to))
        print("%c -> %c" % (fromm, to))
    else:
        hanoimove(num-1, fromm, to, by)
        #print("%d이 %c에서 %c로 이동 " % (num, fromm, to)) 
        print("%c -> %c" % (fromm, to))
        hanoimove(num-1, by, fromm, to)
 
hanoimove(4,'A','B','C')
print(cnt)