Q.3.4 To solve the problem of hanoi

Q: 

In the classic problem of the Towers of Hanoi, you have 3 rods 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 (e.g., each disk sits on top of an even larger one). You have the following constraints:

  • Only one disk can be moved at a time.
  • A disk is slid off the top of one rod onto the next rod.
  • A disk can only be placed on top of a larger disk.

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

A:

起始状态 :(1~n, 0, 0)

中间状态:(n, 1~n-1, 0)

中间状态:(0, 1~n-1, n)

最后状态:(0, 0, 1~n)

因为要用栈处理,所以将后面的状态先入栈。

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

typedef struct node {
	int start;
	int end;
	char src;
	char bri;
	char des;
	node() {
	}
	node(int a, int b, char A, char B, char C):start(a), end(b), src(A), bri(B), des(C){
		
	}
}node;

void hanoi(int start, int end, char src, char bri, char des) {
	stack<node> mstack;
	if (end == start) {
		cout<<"Move disk "<<start<<" from "<<src<<" to "<<des<<endl;
		return ;
	}
	mstack.push(node(start, end, src, bri, des));
	while (!mstack.empty()) {
		node tmp = mstack.top();
		mstack.pop();
		if (tmp.start != tmp.end) {
			mstack.push(node(tmp.start, tmp.end-1, bri, src, des));
			mstack.push(node(tmp.end, tmp.end, src, bri, des));
			mstack.push(node(tmp.start, tmp.end-1, src, des, bri));
		} else {
			cout<<"Move disk "<<tmp.start<<" from "<<tmp.src<<" to "<<tmp.des<<endl;
		}
	}
}

int main(){
    int n = 3;
    hanoi(1, n, 'A', 'B', 'C');
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值