深さも印字するバージョン。
#include <stdio.h>
#define N 6
void hanoi(int depth, int n, int from, int to);
main() {
hanoi(0, N, 0, 1);
return 0;
}
void hanoi(int depth, int n, int from, int to) {
if (n == 1) {
printf("深さ %2d: 円板 1 を %d から %d へ移動します.\n", depth, from, to);
} else {
hanoi(depth+1, n-1, from, 3 - from - to);
printf("深さ %2d: 円板 %d を %d から %d へ移動します.\n", depth, n, from, to);
hanoi(depth+1, n-1, 3 - from - to, to);
}
}
別バージョン。
#include <stdio.h>
#define N 10 /* 円盤の枚数 */
void hanoi(int n, int from, int to);
void print(void);
int a[N+1];
int count = 0;
main() {
print();
hanoi(N, 0, 1);
return 0;
}
/* 円盤 1 から i までを棒 from から棒 to へ移す */
void hanoi(int n, int from, int to) {
if (n == 1) {
a[1] = to; count++; print();
} else {
hanoi(n-1, from, 3 - from - to);
a[n] = to; count++; print();
hanoi(n-1, 3 - from - to, to);
}
}
void print(void) {
int i;
printf("%10d: ", count);
for (i = 1; i <= N; i++) {
printf("%d", a[i]);
}
printf("\n");
}
core... という名前のファイルができたら消しておいてください。