本文介绍了禁止从源头到目的地的河内塔(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个递归C函数,该函数将解决Hanoi塔,但有一个额外的限制,即禁止将光盘从A(源塔)移动到C(目标塔),反之亦然.例如,将一张光盘从A移到C或将C移到A会需要使用辅助塔架(B).

I am trying to write a recursive C function which would solve the tower of Hanoi , but with an extra restriction , that moving a disc from A (the source tower) to C (the destination tower) is forbidden , and vice versa.For instance , moving a single disc from A to C or C to A , would require using the auxiliary tower (B).

我从geeksforgeeks找到了一个普通的递归河内塔式代码,并检查了讨论了相同的问题,但是我不了解数学算法(与C函数相比)

I found a normal recursive Hanoi tower code from geeksforgeeks and checked a CS pagewhich discussed the same problem , but I cant understand the mathematical algorithm (compared to a C function)

void tower(int n, char from, char to, char aux)
{
    if (n == 1 && (from=='B' || to=='B'))
    {
        printf("\n Move 1 from %c to %c", from, to);
        return;
    }
    if(n==1) {
       printf("\n Move 1 from %c to %c", from, aux);
       printf("\n Move 1 from %c to %c", aux, to);
       return;
    }

    tower(n-1, from, aux, to);

    if( from == 'B' || to=='B' ){
        printf("\n Move %d from %c to %c", n, from, to);
    }
    else{
        printf("\n Move %d from %c to %c", n, from, aux);
    }

    tower(n-1, aux, to, from);
}

这是geeksforgeeks的功能,已修改为不违反额外的限制,但现在它可以将较大的磁盘移动到较小的磁盘之上.

this is the function from geeksforgeeks , modified to not violate the extra restriction , but now it keeps moving larger disks on top of the smaller disks.

我想知道如何解决此问题,是否可以针对该限制修改此功能?预先感谢!

I am wondering how this can be fixed and whether it is possible to modify this function for that restriction or not?Thanks in advance !

我一次只能移动一张光盘,因此也无法实现某些当前可用的算法.

edit: I am only allowed to move a single disc at a time , so some currently available algorithms cannot be implemented either.

推荐答案

感谢大家!我找到了一个C ++代码,因此我将在此处进行一些修改,以防万一以后有人遇到相同的问题:

thanks everyone!I found a C++ code so I'll post it down here with some modifications in case anyone has the same question later on:

void hanoi(int n,string src, string itm, string des)
{
    if (n>=1){
        hanoi((n-1),src,itm,des);
        cout<<"Move Plate "<<n<<" from "<<src <<" to "<<itm<<"\n";
        hanoi((n-1),des,itm,src);
        cout<<"Move Plate "<<n<<"from "<<itm <<" to "<<des<<"\n";
        hanoi((n-1),src,itm,des);
    }
}

这篇关于禁止从源头到目的地的河内塔(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:13