标签:
程序的来源是参考尹成老师的教学视频,并实践得到结果。
Hanoi的源程序:
#include<stdio.h>
#include<stdlib.h>
#define N 20
int a[N][3] = { 0 };
int count = 0;//计数器
void show(int a[N][3]);//显示作用
void Hanoi(int n, char A, char B, char C);//移动过程,控制
void move(char X, char Y);//移动,连接数据,视图
void show(int a[N][3])
{
printf("%c\t%c\t%c\t\n", ‘A‘, ‘B‘, ‘C‘);
printf("*********************\n");
for (int i = 0; i <N ; ++i)
{
for (int j = 0; j < 3; ++j)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
void Hanoi(int n, char A, char B, char C)
{
if (n < 1)
return;
else if (n == 1)
{
printf("\n%c->%c\n", A, C);//直接移动
move(A, C);
count++;
show(a);
}
else
{
Hanoi(n - 1,A,C,B);//A->B C做中间量。把n-1个全部移动到B上去
printf("\n%c->%c\n", A, C);//直接移动
move(A, C);
count++;
show(a);
Hanoi(n - 1, B, A, C);//把移动到B上的n-1个全部移动到C上去,A为中间量
}
}
void move(char X, char Y)
{
int m = X - 65;
int n = Y - 65;//若Y为C结果为2,表示第多少列。[N-1][n]
int imove = -1;
for (int i = 0; i < N; ++i)
{
if (a[i][m] != 0)
{
imove = i;
break;//找到第一个不为0的数据
}
}
//a[imove][m]
//a[jmove][n]
int jmove;
if (a[N-1][n] == 0)
jmove = N-1;//最后一排
else
{
jmove = 0;
for (int i = 0; i < N; ++i)
{
if (a[i][n] != 0)
{
jmove = i;
break;
}
}
jmove -= 1;//检索第一个不为零的数据
}
int temp = a[imove][m];
a[imove][m] = a[jmove][n];
a[jmove][n] = temp;
}
void main()
{
int n;
printf("Please input:\n");
scanf_s("%d", &n);
for (int i = 0; i < n; ++i)
{
a[N -1 - i][0] = n - i;
}
//创建Hanoi
show(a);
Hanoi(n, ‘A‘, ‘B‘, ‘C‘);
printf("一共移动%d次\n",count);
system("pause");
}
标签:
原文地址:http://blog.csdn.net/qq_33037903/article/details/51365911