3.4 In the classic problem of the Towers of Hanoi, we have 3 Towers and N disks of different sizes which can slide onto a NY Tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of a even Larger one). You have the following constraints:
(1) Only one disk can is moved at a time.
(2) A disk is slid off the top of the one tower onto the next tower.
(3) A disk can only is placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using stacks.
The classic question of the Nottingham, remember the days of the popular day, what Hanoi Ah, hero Altar said Ah, Huarong Road Ah, are the classic song star on the game, at that time still feel Hanoi very difficult to play, the University of learning data structure when the original with recursion so easy to solve. So let's take a look at how recursion is implemented:
If n = 1,
classTower { Public: Tower (inti): _idx (i) {}intIndex () {return_idx;} voidAddintd) {if(!_disks.empty () && _disks.top () <=d) {cout<<"Error Placing Disk"<< D <<Endl; } Else{_disks.push (d); } } voidMovetopto (Tower &t) {inttop =_disks.top (); _disks.pop (); T.add (top); cout<<"Move Disk"<< Top <<" from"<< index () <<" to"<< T.index () <<Endl; } voidMovedisks (intN, Tower &destination, Tower &buffer) { if(N >0) {movedisks (n-1, buffer, destination); Movetopto (destination); Buffer.movedisks (n-1, Destination, * This); } } Private: Stack<int>_disks; int_idx;};intMain () {intn =Ten; Vector<Tower>Towers; for(inti =0; I <3; ++i) {Tower T (i); Towers.push_back (t); } for(inti = n-1; I >=0; --i) {towers[0].add (i); } towers[0].movedisks (N, towers[2], towers[1]); return 0;}
[Careercup] 3.4 Towers of Hanoi Hanoi