搜尋此網誌

[C/C++][河內塔(Hanoi Tower)]

/*
* File Name: HanoiTower.c
* Author: MH
* Since 2011/06/07
* Toolkit: Dev C++
*/

# include <stdlib.h>
# include <stdio.h>

int times=0;

void Hanoi(int N,char A,char B,char C){    // recursive program

    if(N==1){    // the last condition
        printf("圓盤%d : %c -> %c\n", N, A, C);    // the bottomest disk on A moves to C
        times++;
    }

    else{
        Hanoi(N-1, A, C, B);    // continue moving

        printf("圓盤%d : %c -> %c\n", N, A, C);
        times++;

        Hanoi(N-1, B, A, C);    // second moving
    }
}

int main(){

    int N;

    printf("How many disks?\n");
    scanf("%d", &N);

    while(N>10){    // N is less 10
        system("CLS");
        printf("N should less than 10\n");
        printf("Please input again\n\n");
        scanf("%d", &N);    // input again
    }
    printf("\n");
    Hanoi(N, 'A', 'B', 'C');    // call sub-program

    printf("\n共用了%3d 步\n\n", times);

    system("PAUSE");
    return 0;
}

2 則留言: