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;
}
本文介绍了一个经典的汉诺塔问题,并提供了一种使用栈数据结构来解决该问题的程序实现方案。通过递归算法,文章详细展示了如何将不同大小的盘子从一个柱子移动到另一个柱子上,同时遵循汉诺塔的基本规则。
5678

被折叠的 条评论
为什么被折叠?



