62,253
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HanoiProgram
{
class Program
{
static long count = 0;
static void move(char x,char y)
{
Console.WriteLine("{0}--->{1}",x,y);
}
static void hanoi(int n,char one,char two,char three)
{
if (n == 1)
{
count+=2;
move(one, two);
move(two, three);
}
else
{
count += 2;
hanoi(n - 1, one,two,three);
move(one, two);
hanoi(n - 1, three,two,one);
move(two,three);
hanoi(n - 1, one, two, three);
}
}
static void Main(string[] args)
{
Console.WriteLine("需要搬几个盘子");
int n =int.Parse(Console.ReadLine());
hanoi(n, 'A', 'B', 'C');
Console.WriteLine("搬迁结速;一共进行了{0}次的搬迁。", count);
Console.Read();
}
}
}
#include<stdio.h>
void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle);
int i=0;
void main()
{
unsigned n;
printf("please enter the number of disc:");
scanf("%d",&n); /*输入N值*/
printf("\tneedle:\ta\t b\t c\n");
movedisc(n,'a','c','b'); /*从A上借助B将N个盘子移动到C上*/
printf("\t Total: %d\n",i);
}
void movedisc(unsigned n,char fromneedle,char toneedle,char usingneedle)
{
if(n>0)
{
movedisc(n-1,fromneedle,usingneedle,toneedle);
/*从fromneedle上借助toneedle将N-1个盘子移动到usingneedle上*/
++i;
switch(fromneedle) /*将fromneedle 上的一个盘子移到toneedle上*/
{
case 'a': switch(toneedle)
{
case 'b': printf("\t[%d]:\t%2d.........>%2d\n",i,n,n);
break;
case 'c': printf("\t[%d]:\t%2d...............>%2d\n",i,n,n);
break;
}
break;
case 'b': switch(toneedle)
{
case 'a': printf("\t[%d]:\t%2d<...............>%2d\n",i,n,n);
break;
case 'c': printf("\t[%d]:\t %2d........>%2d\n",i,n,n);
break;
}
break;
case 'c': switch(toneedle)
{
case 'a': printf("\t[%d]:\t%2d<............%2d\n",i,n,n);
break;
case 'b': printf("\t[%d]:\t%2d<........%2d\n",i,n,n);
break;
}
break;
}
movedisc(n-1,usingneedle,toneedle,fromneedle);
/*从usingneedle上借助fromneedle将N-1个盘子移动到toneedle上*/
}
}