三色汉诺塔

Posted 天秤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三色汉诺塔相关的知识,希望对你有一定的参考价值。

/*
三色汉诺塔 
*/

#include <stdio.h>

void hanoi(int disks, char source, char temp, char target)
{
    if(disks == 1)
    {
        printf("move disk from %c to %c \n", source ,target);
        printf("move disk from %c to %c \n", source ,target);
        printf("move disk from %c to %c \n", source ,target);
    }
    else
    {
        hanoi(disks - 1, source, target, temp);
        hanoi(1, source, temp, target);
        hanoi(disks - 1, temp, source, target);
    }
}

void hanoi3colors(int disks)
{
    char source = A;
    char temp = B;
    char target = C;
    int i;
    if(disks == 3)
    {
        printf("move disk from %c to %c \n", source , temp);
        printf("move disk from %c to %c \n", source , temp);
        printf("move disk from %c to %c \n", source , target);
        printf("move disk from %c to %c \n", temp , target);
        printf("move disk from %c to %c \n", temp , source);
        printf("move disk from %c to %c \n", target , temp);
    }
    else
    {
        hanoi(disks / 3 - 1, source, temp, target);
        printf("move disk from %c to %c \n", source, temp);
        printf("move disk from %c to %c \n", source, temp);
        printf("move disk from %c to %c \n", source, temp);
        
        hanoi(disks / 3 - 1, target, temp, source);
        printf("move disk from %c to %c \n", temp , target);
        printf("move disk from %c to %c \n", temp , target);
        printf("move disk from %c to %c \n", temp , target);
        
        hanoi(disks / 3 - 1, source, target, temp);
        printf("move disk from %c to %c \n", target , temp);
        printf("move disk from %c to %c \n", target , temp);
        
        hanoi(disks / 3 - 1, temp, source, target);
        printf("move disk from %c to %c \n", source , temp);
        
        for(i = disks / 3 - 1; i > 0; i--)
        {
            if(i > 1)
            {
                hanoi(i - 1, target, source, temp);
            }
            printf("move disk from %c to %c \n", target, source);
            printf("move disk from %c to %c \n", target, source);
            if(i > 1)
            {
                hanoi(i - 1, temp, source, target);
            }
            printf("move disk from %c to %c \n", source, temp);
        }
    }
}

int main()
{
    int n;
    printf("请输入盘数:");
    scanf("%d", &n);
    
    hanoi3colors(n);
    
    return 0;
}

 

以上是关于三色汉诺塔的主要内容,如果未能解决你的问题,请参考以下文章

代写Haskell程序 汉诺塔汉诺塔编程代码代写

python汉诺塔非递归

C语言汉诺塔问题

汉诺塔问题的详解-附代码

python3汉诺塔简单实现代码

汉诺塔(代码记录+注释)