-
Notifications
You must be signed in to change notification settings - Fork 0
/
#128.py
37 lines (31 loc) · 874 Bytes
/
#128.py
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
32
33
34
35
36
37
def towers_of_hanoi(n):
memo = {}
def move(src, dest):
global num_moves
num_moves += 1
return (src, dest)
def recursive_move(n, src, dest, spare):
# use memoized value if possible
key = (n, src, dest)
if key in memo:
return memo[key]
ret = []
# Base case: move 1 block
if n == 1:
ret.append(move(src, dest))
else:
# move all blocks smaller than n to spare
ret += recursive_move(n-1, src, spare, dest)
# move n to dest
ret.append(move(src, dest))
# move all blocks on spare to dest
ret += recursive_move(n-1, spare, dest, src)
memo[key] = ret
return memo[key]
return recursive_move(n, 1, 3, 2)
if __name__ == "__main__":
num_moves = 0
n = int(input())
result = towers_of_hanoi(n)
output = "\n".join(["Move {} to {}".format(src, dest) for src, dest in result]) + "\nTook {} moves".format(num_moves)
print(output)