汉诺塔

汉诺塔

#include <stdio.h>
#include <time.h>

#define N 5


void solve();
void move(char a, char b, char c, int num);
void print_hanoi();

int main(int argc, char** argv) {
    clock_t begin, end;
    begin = clock();
    solve();
    end = clock();
    printf("%d pans, time cost: %.3f ms\n", N, (end-begin)*1000./CLOCKS_PER_SEC);

    return 0;
}

void solve() {
    move('a', 'b', 'c', N);
}

void move(char a, char b, char c, int num) {
    if (num == 1) {
        printf("%c -> %c\n", a, b);
        return;
    }
    move(a, c, b, num - 1);
    move(a, b, c, 1);
    move(c, b, a, num - 1);
}

测试:

a -> b
a -> c
b -> c
a -> b
c -> a
c -> b
a -> b
a -> c
b -> c
b -> a
c -> a
b -> c
a -> b
a -> c
b -> c
a -> b
c -> a
c -> b
a -> b
c -> a
b -> c
b -> a
c -> a
c -> b
a -> b
a -> c
b -> c
a -> b
c -> a
c -> b
a -> b
5 pans, time cost: 0.072 ms
posted @ 2023-08-13 16:34  keep-minding  阅读(10)  评论(0编辑  收藏  举报