📄 汉诺塔1.cpp
字号:
#include <iostream>
#include <stdlib.h>
using namespace std;
void swap(int,int **); //函数原型
int t = 0; //全局变量
int main()
{
int *p[3]; //声明一个指针数组(每一个元素都是指针),因为p是一个一维数组名,所以p是一个指针,又因为数组p的每一个元素都是指针,所以p是一个二维指针(指向指针的指针)
int c[3][16] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //声明一个二维数组
p[0] = c[0]; //一维数组的数组名是指向数组中第一个元素的指针,是个一维指针;二维数组的数组名没有意义,不是二维指针
p[1] = c[1];
p[2] = c[2];
swap(16, p);
for(int count=0; count<16; count++)
cout<<c[2][count]<<endl;
system("PAUSE");
return 0;
}
void swap(int n,int ** a)
{
if(n==1)
a[(t+2)%3][0] = a[t][0];
else if(n==2)
{
a[(t+1)%3][0] = a[t][0];
a[(t+2)%3][1] = a[t][1];
a[(t+2)%3][0] = a[(t+1)%3][0];
}
else
{
swap(n-2, a);
t=0; //此处t=0可以不要,因为在此处t总是等于0
a[(t+1)%3][n-2] = a[t][n-2];
t=2;
swap(n-2, a);
t=0;
a[(t+2)%3][n-1] = a[t][n-1];
t=1;
swap(n-2, a);
t=0;
a[(t+2)%3][n-2] = a[(t+1)%3][n-2];
swap(n-2, a);
}
}
/*前n-2个移动四次 第n-1个移动两次 第n个(最后一个)移动一次
前n-2个从a柱移到c柱 swap(n-2)
第n-1个从a柱移到b柱 temp=0 (temp+1)%3=temp //此处t=0可以不要,因为在此处t总是等于0
前n-2个从c柱移到b柱 temp=2 swap(n-2)
第n个从a柱移到c柱 temp=0 (temp+2)%3=temp
前n-2个从b柱移到a柱 temp=1 swap(n-2)
第n-1个从b柱移到c柱 temp=0 (temp+2)%3=(temp+1)%3
前n-2个从a柱移到c柱 swap(n-2)
if(n==1)
a[(t+2)%3][0] = a[t][0];
else(n==2)
{
a[(t+1)%3][0] = a[t][0];
a[(t+2)%3][1] = a[t][1];
a[(t+2)%3][0] = a[(t+1)%3][0];
}*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -