汉诺塔
C ++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
void hanoi(int n, char a, char b, char c){
if(n){
hanoi(n - 1, a, c, b);
printf("plate %d from %c to %c\n", n, a, b);
hanoi(n - 1, c, b, a);
}
}
int main(){
int n;
printf("please input the number of plates:\n");
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
实验结果
输入: 1
please input the number of plates:
plate 1 from A to B
输入: 2
please input the number of plates:
plate 1 from A to C
plate 2 from A to B
plate 1 from C to B
输入: 3
please input the number of plates:
plate 1 from A to B
plate 2 from A to C
plate 1 from B to C
plate 3 from A to B
plate 1 from C to A
plate 2 from C to B
plate 1 from A to B
输入: 4
please input the number of plates:
plate 1 from A to C
plate 2 from A to B
plate 1 from C to B
plate 3 from A to C
plate 1 from B to A
plate 2 from B to C
plate 1 from A to C
plate 4 from A to B
plate 1 from C to B
plate 2 from C to A
plate 1 from B to A
plate 3 from C to B
plate 1 from A to C
plate 2 from A to B
plate 1 from C to B