Search code examples
c++recursiontowers-of-hanoi

Towers of Hanoi question


I read through a few of the discussions about the Towers of Hanoi problem. I understand the recursive solution using the following code:

void Hanoi3(int nDisks, char source, char intermed, char dest)
{
    if(nDisks == 1){
        cout << "Move the plate from " << source << " to " << dest << endl; 
    }
    else{
        Hanoi3(nDisks - 1, source, dest, intermed); 
        cout << "Move the plate from " << source << " to " << dest << endl; 
        Hanoi3(nDisks - 1, dest, intermed, source); 
    }
}

What I actually need to do is output some type of "illustration" of the towers at each step. I'm having a lot of trouble accomplishing this. Our instructor suggested using stacks to keep track of what disk is on what tower, but I'm having trouble outputting this as finding and outputting the values in the stacks requires popping off the top entries and deleting them. They become lost, if I understand it correctly.

Either way, it led me to some solution that starts off like this:

void Hanoi(int nDisks, stack<int> source, stack<int> intermed, stack<int> dest){
    if(nDisks == 1){
        dest.push(source.top()); 
        source.pop(); 
    }
    else{
        Hanoi(nDisks - 1, source, dest, intermed); 
        dest.push(source.top()); 
        source.pop(); 
        Hanoi(nDisks - 1, dest, intermed, source); 
    }
}

int main()
{

    int nDisks; 
    cout << "Enter the number of disks:    "; 
    cin >> nDisks; 

    stack<int> source, intermed, dest; 

    for(int i = nDisks; i >= 1; i--){
        source.push(i); 
    }

    Hanoi(nDisks, source, intermed, dest); 

    return 0;
}

I'm well aware that this is wrong. I'm not sure where a good place would be to populate source with the disk numbers. And I'm passing down the same size source stack each time. If someone could give me some direction or anything, that would be really cool. Thank you.


Solution

  • Pass a reference to the stacks:

    stack<int>&
    

    Also consider using a vector rather than a stack so you can iterate it to see the current content of the towers.

    PigBen's answer also correctly identifies a bug in your code where you're not moving the disks from the intermediate tower to the destination tower.