C言語でハノイの塔を解くコードを書く方法
C言語でハノイの塔のコードは次のように書くことができます。
#include <stdio.h>
// 定义移动盘子的函数
void move(int n, char from, char to, char temp) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
move(n - 1, from, temp, to);
printf("Move disk %d from %c to %c\n", n, from, to);
move(n - 1, temp, to, from);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
printf("Steps to solve the Hanoi Tower problem:\n");
move(n, 'A', 'C', 'B');
return 0;
}
このコードでは、move関数がハノイの塔の移動ロジックを実装します。再帰的に、上のn-1個の円盤をfromの棒からtempの棒へ移動します。そして、一番下のn番目の円盤をfromの棒からtoの棒へ移動します。最後に、tempの棒へ移動していたn-1個の円盤をtempの棒からtoの棒へ移動します。そして、main関数では、ユーザは円盤の数を設定し、それからmove関数を呼び出してハノイの塔の問題を解決します。このプログラムは、各円盤を移動するステップを出力します。