ハノイの塔 C言語 再帰アルゴリズム【コード解説付き】

以下是一个C语言汉诺塔递归算法的代码示例:

#include <stdio.h>

void hanoi(int n, char from, char to, char aux) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", from, to);
        return;
    }
    
    hanoi(n-1, from, aux, to);
    printf("Move disk %d from %c to %c\n", n, from, to);
    hanoi(n-1, aux, to, from);
}

int main() {
    int n;
    printf("Enter the number of disks: ");
    scanf("%d", &n);
    
    hanoi(n, 'A', 'C', 'B');
    
    return 0;
}

このコードは、再帰的な方法を使用してハノイの塔の問題を解決しています。 関数hanoiは、移動するディスクの数を示すパラメータn、開始柱を示すfrom、目標柱を示すto、補助柱を示すauxを受け取ります。 各再帰では、n-1個のディスクを開始柱から補助柱に移動し、最後の1つのディスクを開始柱から目標柱に移動し、最後にn-1個のディスクを補助柱から目標柱に移動します。 メイン関数では、ディスクの数を入力し、hanoi関数を呼び出して問題を解決します。

bannerAds