[Careercup] 3.4 Towers of Hanoi Hanoi

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.