C++實(shí)現(xiàn)遞歸的算法,具體代碼如下:
# include <stdio.h>
void move(char A, int n, char C)
{
printf("%d: %c-->%c\n", n, A, C);
}
void Hanoi(int n, char A, char B, char C)
{
if (n == 1)
move(A, 1, C);
else
{
Hanoi(n-1, A, C, B);
move(A, n, C);
Hanoi(n-1, B, A, C);
}
}
int main(void)
{
int n;
char ch1 = 'A', ch2 = 'B', ch3 = 'C';
printf("請輸入要移動的盤子的個數(shù):");
scanf("%d", &n);
Hanoi(n, 'A', 'B', 'C');
return 0;
}
更多信息請查看IT技術(shù)專欄