Last active
June 2, 2019 15:02
-
-
Save JustinSDK/982b1d8568b17ad251715f731b2c7cd6 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
def hanoi(n, a, b, c): | |
param_stack_recursion2 = [[n, a, b, c]] | |
while param_stack_recursion2: | |
m, pa, pb, pc = param_stack_recursion2.pop() | |
param_stack_recursion1 = [] | |
while True: | |
if m == 1: | |
print(pa, pc) # hanoi(1, A, B, C) | |
# hanoi(m - 1, A, C, B) is completed | |
leng = len(param_stack_recursion2) | |
while param_stack_recursion1: | |
m = m + 1 | |
sa, sb, sc = param_stack_recursion1.pop() | |
# hanoi(m - 1, B, A, C) | |
param_stack_recursion2.insert(leng, [m - 1, sb, sa, sc]) | |
if param_stack_recursion2: | |
_, mb, ma, mc = param_stack_recursion2[-1] | |
print(ma, mc) # move A to C | |
break | |
param_stack_recursion1.append([pa, pb, pc]) | |
# hanoi(m - 1, A, C, B) | |
m = m - 1 | |
pa, pb, pc = pa, pc, pb | |
hanoi(4, 'A', 'B', 'C') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment