Tower of Hanoi with forbidden move from source to destination (C)

烂漫一生 提交于 2020-06-29 03:57:28

问题


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).

I found a normal recursive Hanoi tower code from geeksforgeeks and checked a CS page which 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);
}

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.


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/59105164/tower-of-hanoi-with-forbidden-move-from-source-to-destination-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!