河内之塔是一个数学难题,其中我们有三个杆和n个盘。难题的目的是遵循以下简单规则将整个堆栈移动到另一根杆:
1)一次只能移动一个磁盘。
2)每步都包括从一个堆栈中取出上部磁盘并将其放在另一个堆栈的顶部,即,只有当磁盘是堆栈中最上面的磁盘时,才能移动该磁盘。
3)请勿在较小的磁盘上放置任何磁盘。
C/C++
#include
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods
return 0;
}
Output:Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Please refer complete article on Program for Tower of Hanoi for more details!Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.