三柱汉诺塔
#include<stdio.h>
#include<algorithm>
using namespace std;
//a,b,c代表三根柱子,n代表几个圆盘
void hanoi(int n,int a,int b,int c)
{
if(n > 0)
{
hanoi(n-1,a,c,b);
printf("\n%d号 -->> %d号\n",a,b);
hanoi(n-1,c,b,a);
}
}
int main()
{
int n;
while(~scanf("%d",&n)){
hanoi(n,1,2,3);
printf("\n-------------\n");
}
return 0;
}
四柱汉诺塔
#include<stdio.h>
#include<algorithm>
using namespace std;
int k,step;
//a,b,c代表三根柱子,n代表几个圆盘
void threeHanoi(int n,int a,int b,int c)
{
if(n > 0)
{
threeHanoi(n-1,a,c,b);
printf("%d号 -->> %d号\n",a,b);
step++;
threeHanoi(n-1,c,b,a);
}
}
//把a的上面n个通过c和d移到b上
void fourHanoi(int n,int a,int b,int c,int d)
{
if(n >= k)
{
fourHanoi(n-k,a,d,b,c);
threeHanoi(k,a,b,c);
fourHanoi(n-k,d,b,a,c);
}else{
threeHanoi(n,a,b,c);
}
}
int main()
{
int n,a[100];
while(~scanf("%d",&n)){
/*
看k等于几递归步数最少
for(int i=1;i<=n;i++)
{
step = 0;
k = i;
fourHanoi(n,1,2,3,4);
a[i] = step;
}
int min = 999999;
for(int i=1;i<=n;i++){
if(a[i] < min){
min = a[i];
k = i;
}
}
printf("step:%d\n-------------\n",min);
*/
step = 0;
k = 2;
fourHanoi(n,1,2,3,4);
printf("step:%d\n-------------\n",step);
}
return 0;
}