通过数学归纳法可知,无分色汉诺塔与不违反双色汉诺塔规则三,这样无分色汉诺塔代码是和双色汉诺塔代码相同。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int i = 0;
ofstream f1("output.txt");
void move(int n, char a, char b)
{
cout << "Move sheet " << n << " from " << a << " to " << b << endl;
i++;
if (!f1)
cout << "打不开文件" << endl;
f1 << n << " " << a << " " << b << endl;
}
void hanoi(int n, char a, char b, char c)
{
if (n > 0)
{
hanoi(n - 1, a, c, b);
move(n, a, b);
hanoi(n - 1, c, b, a);
}
}
void main()
{
int a;
ifstream fin("input.txt");//输入流对象
ifstream finu("input.txt");//取文本内容对象
finu >> a;//取出文本内容
ofstream("output.txt").close();//清除文本内容
hanoi(a, 'A', 'B', 'C');
}
输入及输出:
![]() | ![]() | ![]() |