汉诺塔问题

汉诺塔Demo Page

The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

 

Origins

The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a legend about an Indian temple which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the rules of the puzzle, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move of the puzzle is completed, the world will end. It is not clear whether Lucas invented this legend or was inspired by it. If the legend were true, and if the priests were able to move disks at a rate of one per second, using the smallest number of moves, it would take them 264−1 seconds or roughly 585 billion years;[1] it would take 18,446,744,073,709,551,615 turns to finish. There are many variations on this legend. For instance, in some tellings, the temple is a monastery and the priests are monks. The temple or monastery may be said to be in different parts of the world — including Hanoi, Vietnam, and may be associated with any religion. In some versions, other elements are introduced, such as the fact that the tower was created at the beginning of the world, or that the priests or monks may make only one move per day. The Flag Tower of Hanoi may have served as the inspiration for the name.

 

Towers of Hanoi Recursive Algorithm

代码
#include "stdafx.h"
#include
<stdio.h>

int count=0;//移动次数
#define N 6 //盘子个数
void Hanoi(int n,char a,char b,char c);
void main()
{
Hanoi(N,
'A','B','C');
getchar();
}
void Hanoi(int n,char a,char b,char c)
{
if(n==0)return;
Hanoi(n
-1,a,c,b);
count
++;
printf(
"次数%d\t第%d个盘子%c从移动%c\n",count,n,a,c);
Hanoi(n
-1,b,a,c);
}
posted on 2010-10-01 21:55  几度夕阳红了  阅读(419)  评论(1)    收藏  举报