CareerCup 3.4

3.4 In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.

(2) A disk is slid off the top of one tower onto the next rod;

(3) A disk can only be placed on top of a larger disk.

Write a program to move the disks from the first tower to the last using Stacks.

#include <iostream>
#include <stack>
using namespace std;

class Tower {
private:
    stack<int> s;
    int index;
public:
    Tower(int idx) : index(idx) {}
    int getIndex() {
        return index;
    }
    void push(int disk) {
        s.push(disk);
    }
    int pop() {
        int disk = s.top();
        s.pop();
        return disk;
    }
};

void Hanoi(int n, Tower &from, Tower &to, Tower &use) {
    if (n > 0) {
        Hanoi(n - 1, from, use, to);
        int disk = from.pop();
        cout << "Move disk " << disk << " from " << from.getIndex() << " to " << to.getIndex() << endl;
        to.push(disk);
        Hanoi(n - 1, use, to, from);
    }
}

int main()
{
   Tower from(1);
   Tower use(2);
   Tower to(3);
   int n = 3;
   for (int i = n; i > 0; i--) {
       from.push(i);
   }
   Hanoi(n, from, to, use);
   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值