The examples in this article share the specific code of python solving the Tower of Hanoi game for everyone for your reference. The specific content is as follows
1. Problem definition
Baidu Encyclopedia Definition: The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy derived from an ancient legend in India. It is said that when the Great Brahma created the world, he made three diamond pillars. On one pillar, 64 golden discs were stacked in order from small to large. The Brahma ordered the Brahmin to use one of the pillars to reposition the 64 golden discs on the third pillar. It also stipulates that the golden disc that cannot be enlarged on the small golden disc can only be moved one disc at a time between the three pillars.
For example, if the golden disc has only 3 pieces, in order to meet the rules of the game, it must be completed in 8 steps as shown in the following figure:
Two, code implementation
# Move n plates from x column to z column with the help of y column
def hanoi(n, x, y, z):
count =0if n ==1: #Recursive exit
print(x,' -- ', z)return1else:
# Before n-1 plate is moved from the x column to the y column with the help of the z column
count +=hanoi(n -1, x, z, y) #Recursive call
# Move the bottom 1 plate from the x-pillar to the z-pillar
count +=hanoi(1, x, y, z)
# Will n-1 plate is moved from the y column to the z column with the help of the x column
count +=hanoi(n -1, y, x, z) #Recursive call
return count
def main():
hanoi_level =input("Please enter the number of floors of the Tower of Hanoi:")print("The total number of moves is%d"%hanoi(int(hanoi_level),'X','Y','Z'))if __name__ =='__main__':main()
When the golden disc has 4 layers, the output result of the code is:
Please enter the number of floors of the Tower of Hanoi: 4
X -- Y
X -- Z
Y -- Z
X -- Y
Z -- X
Z -- Y
X -- Y
X -- Z
Y -- Z
Y -- X
Z -- X
Y -- Z
X -- Y
X -- Z
Y -- Z
The total number of moves is 15
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts