汉诺塔解法

/*
 * hanoi.c
 */
#include <stdio.h>
#include <stdlib.h>

int m_count = 0;

void hanoi(int n, char from, char pass, char to)
{
    if (n == 0)
        return;

    m_count ++;

    if (n == 1)
        printf("%d: %c -> %c\n", n, from, to);
    else {
        hanoi(n-1, from, to, pass); 
        printf("%d: %c -> %c\n", n, from, to);
        hanoi(n-1, pass, from, to); 
    }
}

int main(int argc, char **argv)
{
    int n = 0;
    if (argc < 2) {
        printf("usage: %s n\n", argv[0]);
        return 1;
    }

    n = atoi(argv[1]);
    hanoi(n, 'A', 'B', 'C');
    printf("count: %d\n", m_count);
    
    return 0;
}

你可能感兴趣的:(汉诺塔解法)