C下:
#include <stdio.h>
#include <stdlib.h>
void PrintWelcomeInfo();
void MoveHanoi( unsigned int n, char * from, char * tmp, char * to);
void MovePlate( unsigned int n, char * from, char * to);
int main()
{
unsigned int n;
PrintWelcomeInfo();
scanf( "%d",&n );
MoveHanoi( n, "X", "Y", "Z" );
return 0;
}
void PrintWelcomeInfo()
{
printf("The program shows the moving process of Hanoi Tower.\n");
printf("Input number of plates:");
}
void MovePlate( unsigned int n, char * from, char * to)
{
printf( "%d: %s --> %s\n", n, from, to );
}
void MoveHanoi( unsigned int n, char * from, char * tmp, char * to )
{
if( n == 1 )
MovePlate( n,from,to);
else{
MoveHanoi( n - 1, from, to, tmp ); /*塔从from杆经to杆移动到tmp杆*/
MovePlate( n, from, to ); /*盘从from杆移动到to杆*/
MoveHanoi( n - 1, tmp, from, to ); /*塔从tmp杆经from杆移动到to杆*/
}
}
如果不想使用字符指针,且有zylib库,注意zylib函数是自己定义的,可以修改成如下:
#include <stdio.h>
#include <stdlib.h>
#include "zylib.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/* 枚举类型 HANOI,其文字分别表示三个圆柱的代号 */
typedef enum {X, Y, Z} HANOI;
void PrintWelcomeInfo();
unsigned int GetInteger( STRING prompt );
void MoveHanoi( unsigned int n, HANOI from, HANOI tmp, HANOI to );
STRING ConvertHanoiToString( HANOI x );
void MovePlate( unsigned int n, HANOI from, HANOI to );
int main()
{
unsigned int n;
PrintWelcomeInfo();
n = GetInteger( "Input number of plates: " );
MoveHanoi( n, X, Y, Z );
return 0;
}
void PrintWelcomeInfo()
{
printf( "The program shows the moving process of Hanoi Tower.\n" );
}
unsigned int GetInteger( STRING prompt )
{
unsigned int t;
printf( prompt );
t = GetIntegerFromKeyboard();
return t;
}
STRING ConvertHanoiToString( HANOI x )
{
switch( x ){
case X: return "X";
case Y: return "Y";
case Z: return "Z";
default: return "Error";
}
}
void MovePlate( unsigned int n, HANOI from, HANOI to )
{
STRING from_str, to_str;
from_str = ConvertHanoiToString( from );
to_str = ConvertHanoiToString( to );
printf( "%d: %s --> %s\n", n, from_str, to_str );
}
void MoveHanoi( unsigned int n, HANOI from, HANOI tmp, HANOI to )
{
if( n == 1 )
MovePlate( n, from, to );
else{
MoveHanoi( n - 1, from, to, tmp ); /*塔从from杆经to杆移动到tmp杆*/
MovePlate( n, from, to ); /*盘从from杆移动到to杆*/
MoveHanoi( n - 1, tmp, from, to ); /*塔从tmp杆经from杆移动到to杆*/
}
}
python下:
# -*-coding=utf-8-*-
def move(n, a, b, c):
if n == 1:
print('move第1个盘从', a, '-->', c)
else:
move(n-1, a, c, b)
print('move第%d个盘从'%n, a, '-->', c)
move(n-1, b, a, c)
n = int(input("这是一个汉诺塔游戏计算程序。请输入层数:\n"))
move(n, 'X', 'Y', 'Z')