The Problem
There are 3 pegs source ,auxillary and target. n disks of different sizes are given which can slide onto any peg . In the beginning all of the disks are in the source peg in the order of size with largest disk at the bottom and smallest disk at the top. We have to move all the disks from source peg to target peg such that in the end the target peg will have all the disks in the same order of size.
Rules:
1. Only one disk can be moved from one peg to another peg at a time
2. A larger disk cannot be placed on top of the smaller disk
C++ Program
#include <iostream> #include <cstdlib> static int moveCounter = 0; void towerOfHanoi(int ndisk, char source, char auxillary, char target) { if(ndisk == 1) { std::cout << "Move [" << ndisk << "] [" << source << "] to [" << target << "]" << std::endl; ++moveCounter; return; } //place ndisk - 1 disks from source to auxillary peg towerOfHanoi(ndisk - 1, source, target, auxillary); //place ndisk to target peg std::cout << "Move [" << ndisk << "] [" << source << "] to [" << target << "]" << std::endl; ++moveCounter; //place ndisk - 1 disks from auxillary to target peg towerOfHanoi(ndisk - 1, auxillary, source, target); } int main(int args, char *argv[]) { if(argv[1] == NULL) { std::cout << "ERROR: Insufficient Arguments\n"; std::cout << "Usage: ./a.out number_of_disks\n"; exit(-1); } int disks = atoi(argv[1]); char peg1 = 'A', peg2 = 'B', peg3 = 'C'; towerOfHanoi(disks, peg1, peg2, peg3); std::cout << "Total Moves = " << moveCounter << std::endl; }
Read more ...