2011年12月20日 星期二

河內塔 - 以堆疊實作



要以相反順序將參數壓入堆疊


#include <stdio.h>

int main(void)
{
    int stackn[50], stacka[50], stackb[50], stackc[50];
    int top, N, n, a, b, c;

    while (scanf("%d", &N) == 1)
    {
        top = 0;
        stackn[top] = N;
        stacka[top] = 'A';
        stackb[top] = 'B';
        stackc[top] = 'C';

        while (top != -1)
        {
            n = stackn[top];
            a = stacka[top];
            b = stackb[top];
            c = stackc[top];
            top--;
            if (n == 1)
            {
                printf("%c -> %c\n", a, c);
            }
            else
            {
                top++;
                stackn[top] = n-1;
                stacka[top] = b;
                stackb[top] = a;
                stackc[top] = c;

                top++;
                stackn[top] = 1;
                stacka[top] = a;
                stackb[top] = b;
                stackc[top] = c;

                top++;
                stackn[top] = n-1;
                stacka[top] = a;
                stackb[top] = c;
                stackc[top] = b;
            }
        }
    }

    return 0;
}

沒有留言:

張貼留言