参考视频:
代码 :
void move(int x, int y)
{
printf("%c->%c ", x, y);
}
//pos1 起始位置
//pos2 中转位置
//pos3 目的位置
void hanoi(int n, char pos1, char pos2, char pos3)
{
if (n == 1)
{
move(pos1, pos3);
}
else
{
hanoi(n - 1, pos1, pos3, pos2);//将 起始位置 的n-1个盘子借助 中转位置 移动到 目标位置
move(pos1, pos3);//将起始位置上 最后一个 盘子移向目标位置
hanoi(n - 1, pos2, pos1, pos3);//将 中转位置 的n-1个盘子借助 起始位置 移动到目标位置
}
}
//move中的实参与hanoi函数中的形参相对应,而hanoi函数中形参a,b,c所对应的值也是在有规律的变化
int main()
{
int n = 0;
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}