Python Algorithm Design - Tower of Hanoi

Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm

Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!

1. Tower of Hanoi

Towers of Hanoi: Simple and classic algorithm with an interesting recursive solution.
insert image description here
The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy that originated from an ancient Indian legend. When Brahma created the world, he made three diamond pillars. On one pillar, 64 gold discs were stacked in order of size from bottom to top. Brahma ordered Brahmin to rearrange the discs on another pillar in order of size from below. And it is stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved between the three pillars at a time. So how to do it with Python?

Let's imagine if we want to move the largest disk to the rightmost column. We need to move the other disks except the largest disk to the middle pillar first. So the problem becomes how to move N-1 disks to the middle pillar. Then we thought of the recursive method.

Move N discs from the left peg to the right peg:

  • Recursively move N-1 discs from the left column to the middle column
  • Move the largest disk from the left column to the right column
  • Recursively move N-1 discs from the middle column to the right column

Python algorithm implementation:

def hanoi(height, left='left', right='right', middle='middle'):
    if height:
        hanoi(height - 1, left, middle, right)
        print(left, '=>', right)
        hanoi(height - 1, middle, right, left)

hanoi(3)

Output result:
insert image description here

2. Source code download

Python algorithm design source code download:

3. Author Info

Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!

Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!

Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!

Guess you like

Origin blog.csdn.net/qq_44000141/article/details/121664596