Description
汉诺塔是一个小游戏,如图,有三根木桩,从左到右分别是1、2、3,有n个盘子,从小到大编号分别为1~n(图中n = 3),初始状态下,n个盘子都在1号木桩上,并且盘子从上到下编号递增。
游戏的目标是把所有盘子从木桩1移动到木桩3上。
游戏规则:
1、 每次只允许移动一个盘子
2、 移动盘子时,编号大的盘子不能移动到编号小的盘子上面,也就是要保持每根木桩上的盘子从上到下都是递增的(任何编号的盘子都能直接移动到空的木桩上)
请写一个程序来完成游戏目标,请注意,程序的输出与图中的输出不同,比图中多了from peg x,x表示木桩编号,如:
Input
第一行是一个数字t,表示有t个测试用例
接下来的t行每一行是一个数字n,表示初始状态有n个盘子在木桩1上
Output
对于每一个用例,输出完成游戏的所有操作,每个移动操作占一行
Sample Input
Copy sample input to clipboard
1 3
Sample Output
move disk 1 from peg 1 to peg 3 move disk 2 from peg 1 to peg 2 move disk 1 from peg 3 to peg 2 move disk 3 from peg 1 to peg 3 move disk 1 from peg 2 to peg 1 move disk 2 from peg 2 to peg 3 move disk 1 from peg 1 to peg 3
Problem Source: 第四周 5班
汉诺塔移动问题,递归实现,下面给出一个闷骚版:
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <string.h>
#include <vector>
#include <iomanip>
#include <map>
#include <stack>
#include <functional>
#include <list>
using namespace std;
vector<vector<int> > p;
int counter;
void moveStep(int n, int from, int to) {
cout << "Step " << counter << " : move disk " << n << " from peg " << from << " to peg " << to << endl;
counter++;
p[from].pop_back();
p[to].push_back(n);
int height = max(p[1].size(), max(p[2].size(), p[3].size()));
cout << "Now the status:" << endl;
for (int i = height - 1; i >= 0; i--) {
for (int j = 1; j <= 3; j++) {
if (i >= p[j].size()) cout << "| |";
else cout << "|" << setw(10) << p[j][i] << "|";
}
cout << endl;
}
cout << "------------------------------------------------" << endl;
cout << "| peg 1|" << "| peg 2|" << "| peg 3|" << endl;
cout << endl;
}
void original(int n) {
int height = max(p[1].size(), max(p[2].size(), p[3].size()));
cout << "The original status : " << endl;
for (int i = height - 1; i >= 0; i--) {
for (int j = 1; j <= 3; j++) {
if (i >= p[j].size()) cout << "| |";
else cout << "|" << setw(10) << p[j][i] << "|";
}
cout << endl;
}
cout << "------------------------------------------------" << endl;
cout << "| peg 1|" << "| peg 2|" << "| peg 3|" << endl;
cout << endl;
}
void han(int n, int from, int mid, int to) {
if (n == 1) {
moveStep(n, from, to);
return;
}
//核心代码
han(n - 1, from, to, mid);
moveStep(n, from, to);
han(n - 1, mid, from, to);
}
int main() {
std::ios::sync_with_stdio(false);
int caseNum;
cin >> caseNum;
while (caseNum--) {
int n;
cin >> n;
p.clear();
p.resize(4);
for (int i = n; i >= 1; i--) p[1].push_back(i);
counter = 1;
cout << "The step(s) for " << n << " disk(s) : " << endl;
cout << "========================================================" << endl;
original(n);
han(n, 1, 2, 3);
cout << "========================================================" << endl;
}
//getchar();
//getchar();
return 0;
}