Towers of Hanoi

Example Code

#include <iostream>
using namespace std;

int moves;

void hanoi(int diskSize, int source, int spare, int dest)
{

    if (diskSize < 1) return;

    cout << "Goal: Move disks 1 to " << diskSize << " from pin " << source << " to pin " << dest << endl;

    //Move all disks smaller than this one over to the spare.
    hanoi(diskSize - 1, source, dest, spare);

    //Move the remaining disk to the destination peg.
    std::cout << "Move disk "  << diskSize << " from peg " << source << " to peg " << dest << endl;
    moves++;
    //Move the disks we just moved to the spare back over to the dest peg.
    hanoi(diskSize - 1, spare, source, dest);
}

int main()
{
    moves = 0;
    //Move all 3 disks from peg 1 to peg 2 using peg 2 as a temporary.
    hanoi(3, 1, 2, 3);
    cout << "Done in " << moves << " moves." << endl;
    return 0;
}
Topic revision: r1 - 2015-12-10 - JimSkon
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback