Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created January 12, 2017 05:46
Show Gist options
  • Save JustinSDK/64e181efe0be38868af2600481d6fa43 to your computer and use it in GitHub Desktop.
Save JustinSDK/64e181efe0be38868af2600481d6fa43 to your computer and use it in GitHub Desktop.
河內塔不使用堆疊的非遞迴版本
def is_even(n):
return n % 2 == 0
def which_disk(n):
c = n ^ (n + 1)
i = 0
while c != 0:
c = c >> 1
i = i + 1
return i
def hanoi(n):
number_of_moves = 2 ** n - 1
dir = [1, 0] if is_even(n) else [0, 1]
pin = [1] * number_of_moves
for i in range(0, number_of_moves):
disk = which_disk(i)
p_idx, d_idx = disk - 1, disk & 1
next = (pin[p_idx] + dir[d_idx]) % 3 + 1
print(pin[p_idx], next)
pin[p_idx] = next
hanoi(4)
@jiro0402
Copy link

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment