LoginSignup
0
0

More than 1 year has passed since last update.

ハノイの塔を解くプログラム python3

Last updated at Posted at 2023-01-26

再帰アルゴリズムで、ハノイの塔を解くプログラムです。

$ chmod +x hanoi.pyで実行権限を付けて実行して下さい。
'./$ hanoi.py <n>で、n段のハノイの塔を解きます。

hanoi.py
#!/usr/bin/python3
import sys

def hanoi(n,from_,to,work):
  if (n>0):
    hanoi(n-1,from_,work,to) 
    print("%s から %s に %d番目のディスクを移動して下さい。" % (from_,to,n))
    hanoi(n-1,work,to,from_)

hanoi(int(sys.argv[1]),' 左','中央',' 右')

実行結果

$ hanoi.py 3
 左 から 中央 に 1番目のディスクを移動して下さい。
 左 から  右 に 2番目のディスクを移動して下さい。
中央 から  右 に 1番目のディスクを移動して下さい。
 左 から 中央 に 3番目のディスクを移動して下さい。
 右 から  左 に 1番目のディスクを移動して下さい。
 右 から 中央 に 2番目のディスクを移動して下さい。
 左 から 中央 に 1番目のディスクを移動して下さい。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0