`
阿尔萨斯
  • 浏览: 4169358 次
社区版块
存档分类
最新评论

算法 - 汉诺塔问题(C++)

 
阅读更多

#include <iostream>

using namespace std;

void print(char A, char C)
{
	cout << A << "-->" << C << endl;
}

void hanoi(int n, char A, char B, char C)
{
	if(n == 1)
	{
		print(A, C);
	}
	else
	{
		hanoi(n - 1, A, C, B);
		print(A, C);
		hanoi(n - 1, B, A, C);
	}
}

int main()
{
	int n;
	cout << "Please input the number of plates in pile A:";
	cin >> n;
	hanoi(n, 'A', 'B', 'C');
	return 0;
}

// Output:
/*
Please input the number of plates in pile A:6
A-->B
A-->C
B-->C
A-->B
C-->A
C-->B
A-->B
A-->C
B-->C
B-->A
C-->A
B-->C
A-->B
A-->C
B-->C
A-->B
C-->A
C-->B
A-->B
C-->A
B-->C
B-->A
C-->A
C-->B
A-->B
A-->C
B-->C
A-->B
C-->A
C-->B
A-->B
A-->C
B-->C
B-->A
C-->A
B-->C
A-->B
A-->C
B-->C
B-->A
C-->A
C-->B
A-->B
C-->A
B-->C
B-->A
C-->A
B-->C
A-->B
A-->C
B-->C
A-->B
C-->A
C-->B
A-->B
A-->C
B-->C
B-->A
C-->A
B-->C
A-->B
A-->C
B-->C
*/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics