Ask Question

Prepare a algorithm visualization for the Tower of Hanoi when 4 disks are to be moved from spindle #1 to spindle #3.

+2
Answers (1)
  1. 2 November, 04:41
    0
    follwing is the code for Tower of Hanoi for n disks.

    #include

    using namespace std;

    void towofhan (int n, char source, char aux, char dest) / /function for tower of hanoi ...

    {

    if (n<0)

    return;

    if (n==1) / /base case.

    {

    cout<<"Move disk 1 from "<
    return;

    }

    towofhan (n-1, source, dest, aux); //recursive call.

    cout<<"move disk "<
    towofhan (n-1, aux, source, dest); //recursive call.

    }

    int main () {

    int n=4;

    towofhan (n,'1','2','3'); //function call.

    return 0;

    }

    Explanation:

    If there is only 1 disk then we have to move the disk from source to destination.

    Then after that we will apply recursion to solve the problem.

    We have to work on only nth disk else will be done by the recursion.

    First call recursion to move n-1 disks from source to auxiliary.

    Then move nth disk from source to destination spindle.

    Now move n-1 disks that are on the auxiliary spindle to destination spindle.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Prepare a algorithm visualization for the Tower of Hanoi when 4 disks are to be moved from spindle #1 to spindle #3. ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers